views:

85

answers:

5

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==..) ?

+4  A: 

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).

Martin York
If don't care about order, you'd still want to change the variable to volatile, no?
Inverse
The use of volatile is compiler architecture dependent in what it means in terms of multi-threading. Read the appropriate documentation.
Martin York
+2  A: 

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.

anon
That's what I was thinking.
GMan
It's plenty useful to initialize some globals before spawning any additional threads, and from that point on the data is shared read but never again written.
Ben Voigt
A: 

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.

Jack
A: 

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?

Lirik
it is just making my code less, i have .ini file that is read and sets the data before threads are started, i need to access that information from multiple threads later, without modifying it :) not useless, the application is very big :))
Tenev
@tenev, I'm not trying to say that what you're doing is useless, but the example you provided us with implies that the second thread will not be doing anything at all because "data" is ALWAYS 5...
Lirik
+1  A: 

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.

Ben Voigt