-
September 21st, 2010, 01:26 PM
#1
Multiple Threads with same variable
Here is what I want to happen:
Create a background thread that polls a DAQ and constantly updates variable VOLTAGE.
Main thread just retrieves latest value stored in VOLTAGE.
I don't really care about synchronization or anything. The two threads are completely independent except the VOLTAGE variable.
Is there any problem with this? How does a computer write to memory... does it write it "bit by bit" ? e.g. is it possible for the main thread to read a half-way updated VOLTAGE value and get incorrect data?
Initial tests seem rock solid, but want to make sure...
Thanks!
Edit: VOLTAGE is just a float array...
Last edited by jnmacd; September 21st, 2010 at 01:36 PM.
-
September 21st, 2010, 01:45 PM
#2
Re: Multiple Threads with same variable
Originally Posted by jnmacd
is it possible for the main thread to read a half-way updated VOLTAGE value and get incorrect data?
You should assume it's possible unless you find documentation documenting otherwise. There are relatively simple mechanisms available to synchronize such a thing.
-
September 21st, 2010, 04:55 PM
#3
Re: Multiple Threads with same variable
Originally Posted by jnmacd
Edit: VOLTAGE is just a float array...
About the only data type that can be changed in an atomic operation in VC is a boolean. Any other data type that is shared between thread (when writing is involved) requires synchronization.
In other words, a float shared between two thread requires synchronized access, and an array of floats definitely does.
Using RAII, it's pretty simple to add thread safety to a std::vector<float>.
All it takes is a couple of synchronization class helpers (AutoLockT is a lock helper that operates on LockableCS, a critical section class wrapper).
To define a thread safe vector, we have:
Code:
class VoltageArray : public std::vector< double >, public LockableCS
{
public:
VoltageArray () {};
~VoltageArray () {};
};
Access the vector for read and write
Code:
void DoSomeThreadSafeOP( )
{
// Lock the array for access (auto-unlock when 'lock' goes out of scope)
AutoLockT< VoltageArray > lock(&m_VoltageArray);
// Read from the array.
double d = m_VoltageArray[ 0 ];
// Write to the array
m_VoltageArray[ 0 ] = d;
}
Keep in mind that you must lock the array for both read and write access. Many devs new to mt programming only lock for writes and forget to lock for reads.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|