look at this code:
int data=5;
void Thread1()
{
if(data==5)
{
//nothing
}
}
void Thread2()
{
if(data==2)
{
//nothing
}
}
in this case, do i need to use EnterCriticalSection/MutexLock before if(data==..) ?
look at this code:
int data=5;
void Thread1()
{
if(data==5)
{
//nothing
}
}
void Thread2()
{
if(data==2)
{
//nothing
}
}
in this case, do i need to use EnterCriticalSection/MutexLock before if(data==..) ?
If you are just reading the data then no locks required.
If you are writing the data AND you care about the order data is read then you need to use CS to make sure the ordering is correct. (Note if the object has a more complex state that is not updated in an atomic operation then you may care more about the ordering of reads/writes).
If nothing ever changes the data, then on most architectures, no you don't. But if nothing ever changes the data, the code is meaningless.
If your example is meant to be already complete then no, you don't have to lock or manage any critical section since you are not modifying anything.
But you example, as it is, it's just pointless..
You don't need to handle concurrency when there are threads that are just reading plain data (things are different on iterable data structures) but this is useful just when you have static data that doesn't need to be changed. As soon as you add just one writer then you have to make sure that when it writes noone is reading, but everyone will still be able to read concurrently with other readers if no writer is doing its work.
You don't need to lock when you're not modifying the shared memory, but your example would be pretty useless since you initialize data
, you check its value, but you never modify it... the second thread is going to be completely useless. Do you modify data
variable anywhere?
If the data is being changed by a different thread, then you need a memory fence when reading it in order to assure consistency. A lock is one way to achieve a memory fence, but not necessarily the optimal one. However, unless you find (through measurement!) that locking is slowing down your program significantly, it's probably not worth worrying about alternatives.