POSIX threads and global variables in C on Linux

advertisements

If I have two threads and one global variable (one thread constantly loops to read the variable; the other constantly loops to write to it) would anything happen that shouldn't? (ex: exceptions, errors). If it, does what is a way to prevent this. I was reading about mutex locks and that they allow exclusive access to a variable to one thread. Does this mean that only that thread can read and write to it and no other?


Would anything happen that shouldn't?

It depends in part on the type of the variables. If the variable is, say, a string (long array of characters), then if the writer and the reader access it at the same time, it is completely undefined what the reader will see.

This is why mutexes and other coordinating mechanisms are provided by pthreads.

Does this mean that only that thread can read and write to it and no other?

Mutexes ensure that at most one thread that is using the mutex can have permission to proceed. All other threads using the same mutex will be held up until the first thread releases the mutex. Therefore, if the code is written properly, at any time, only one thread will be able to access the variable. If the code is not written properly, then:

  • one thread might access the variable without checking that it has permission to do so
  • one thread might acquire the mutex and never release it
  • one thread might destroy the mutex without notifying the other

None of these is desirable behaviour, but the mere existence of a mutex does not prevent any of these happening.

Nevertheless, your code could reasonably use a mutex carefully and then the access to the global variable would be properly controlled. While it has permission via the mutex, either thread could modify the variable, or just read the variable. Either will be safe from interference by the other thread.