space_voyager
space_voyager

Reputation: 2034

Is it thread-safe to read but not write a shared variable?

Using Pthreads, suppose there is a global shared variable foo between threads 1 and 2. Is it thread-safe to read the value of foo from thread 1 without using a mutex? Note that while thread 1 reads foo, it is not impossible that thread 2 may be changing its value (but it would have locked the mutex beforehand of course).

The situation is something like this:

#include <pthread.h>
...
int foo;
pthread_mutex_t mutex;
...

void *thread1(void *t) {
  while (foo<10) {
    // do stuff
  }
  pthread_exit(NULL);
}

void *thread1(void *t) {
  ...
  pthread_mutex_lock(&mutex);
  ...
  foo++;
  ...
  pthread_mutex_unlock(&mutex);
  ...
  pthread_exit(NULL);
}

int main() {
  ...
}

Upvotes: 0

Views: 207

Answers (2)

Michael Burr
Michael Burr

Reputation: 340516

It is not thread safe for a variety of possible reasons, but the one you will likely run into is that the compiler could very well optimize the read of foo into a single read that is hoisted out of the while loop so it will never see a change.

Upvotes: 3

Raskayu
Raskayu

Reputation: 743

If you R/W a value you should sync the writes and the reads, that's because that can make inconsistent reads, like at the start you wanna read foo = 0, but write goes faster so you'll read foo = 1.

In your context that would be having less than 10 iterations in that while, so it's NOT THREAD-SAFE.

Upvotes: 0

Related Questions