Is there a problem with multiple threads using the same integer memory location between pthreads in a C program without any synchronization utilities?
To simplify the issue,
- Only one thread will write to the integer
- Multiple threads will read the integer
This pseudo-C illustrates what I am thinking
void thread_main(int *a) {
//wait for something to finish
//dereference 'a', make decision based on its value
}
int value = 0;
for (int i=0; i<10; i++)
pthread_create(NULL,NULL,thread_main,&value);
}
// do something
value = 1;
I assume it is safe, since an integer occupies one processor word, and reading/writing to a word should be the most atomic of operations, right?
Your pseudo-code is NOT safe.
Although accessing a word-sized integer is indeed atomic, meaning that you’ll never see an intermediate value, but either “before write” or “after write”, this isn’t enough for your outlined algorithm.
You are relying on the relative order of the write to
aand making some other change that wakes the thread. This is not an atomic operation and is not guaranteed on modern processors.You need some sort of memory fence to prevent write reordering. Otherwise it’s not guaranteed that other threads EVER see the new value.