Multiple threads - do I need to block data reading?

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 earlier than ((data == ..)?

+6
c ++ multithreading
source share
5 answers

If you are just reading data, then no locks are required.

If you write AND data, you need to read the order data, then you need to use CS to make sure the order is correct. (Note that if an object has a more complex state that is not updated in an atomic operation, you may need more information about the read / write order).

+6
source share

If nothing ever changes data, then most architectures don’t, you don’t. But if nothing ever changes the data, the code makes no sense.

+1
source share

If the data is being changed by another thread, then you need a memory pickup while reading to ensure consistency. Locking is one way to achieve memory pickup, but not necessarily optimal. However, if you do not find (through measurement!) That locking significantly slows down your program, you probably should not worry about alternatives.

+1
source share

If your example should already be completed, no , you do not need to block or manage any critical section, since you are not changing anything.

But you, for example, an example, it is simply meaningless.

You do not need to handle concurrency when there are streams that just read simple data (different things in iterable data structures), but this is only useful when you have static data that does not need to be changed. As soon as you add only one writer, you you need to make sure that when he writes that no one is reading, but everyone will read at the same time as other readers, if not one writer does his job.

0
source share

You do not need to block when you do not change the shared memory, but your example will be useless, since you initialize data , you check its value, but you never change it ... the second thread will be completely useless. Do you change the data variable anywhere?

0
source share

All Articles