2

Possible Duplicate:
Is mutex needed to synchronize a simple flag between pthreads?

In a POSIX environment I have two threads (initialized with pthread_create()), A and B.

A is sometimes writing into a flag variable (an int) and B is sometimes reading it.

Do I need to protect this variable with a mutex or can those operations always be considered as atomic?

Community
  • 1
  • 1
Guid
  • 2,137
  • 2
  • 20
  • 33
  • possible dup http://stackoverflow.com/questions/7223164/is-mutex-needed-to-synchronize-a-simple-flag-between-pthreads – FoolishSeth Oct 25 '12 at 07:30

2 Answers2

1

You should protect it if the variable is anything more complex than a true/false flag. There's no guarantee that one thread won't read the variable halfway through a write operation.

There are ways to mitigate the non-use of mutex protection in certain circumstances (such as dual-read-and-check-repeatedly if the variable is only ever incrementing) but, for general modifications to a variable, a mutex is better. You don't need to be too concerned about the performance, mutexes are pretty efficient.

Of course, if you absolutely must shave off as much time as possible, there are tricks that can be used but they're rarely portable.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
0

Yes, you need mutex if you are using the flag in both threads. Mutex is must, because assume thread B is doing two operations based on the flag and thread A is keep on updating the flag value. In thread B suppose after completing first operation context switch happens and thread A changes the flag value, thread B will get new flag value for second operation, so mutext is must.

You can minimize locking by maintaining global flag value in threads local memory and update global flag once local operations are completed, the approach depends on your requirement.