user3021085
user3021085

Reputation: 417

pthreads reading and writing to the same variable

I know I am supposed to use mutexes but the way I currently use pthreads it would overly complicate the program...

anyway I basically have a variable which I use to denote if a thread is currently performing work or not. in the main thread I run over it in a while loop the check what threads are no longer busy. Now obviously my thread can write to this same variable once it is done.

Is it allowed to read and write from the same variable from 2 different threads, if 1 thread is ONLY reading and 1 thread is ONLY writing. reading of an old version is not of much concern since it will just read the correct once on the next iteration.

so is it safe to do something like that?

Upvotes: 0

Views: 1101

Answers (1)

pat
pat

Reputation: 12749

In general, NO.

The following article explains why:

http://www.domaigne.com/blog/computing/mutex-and-memory-visibility/

Here is a list of API functions that act as memory barriers:

http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_11

Upvotes: 2

Related Questions