2

I'm using Glib's mutex utilities to handle concurrency. Is it guaranteed that the updated version of a modified variable will be visible to any other thread after unlocking a mutex? Do these threads have to acquire a lock on the mutex as well in order to read it safely?

GStaticMutex mutex;
int value;

void init() {
  g_static_mutex_init(&mutex);
  value = 0;
}

void changeValue() {
  g_static_mutex_lock(&mutex);
  value = generateRandomNumber();
  g_static_mutex_unlock(&mutex);
}
Markus Kramer
  • 411
  • 5
  • 13
  • 2
    Yes, that's the whole point of a mutex. Without this, mutexes would be useless. A mutex is always a full memory barrier. – R.. GitHub STOP HELPING ICE Jan 17 '12 at 22:52
  • In my understanding mutual exclusion (mutex) and visibility are separate things. So it would make some sense. Maybe post your comment as an answer. – Markus Kramer Jan 18 '12 at 10:22
  • The only (or at least main) reason mutual exclusion is useful is to synchronize data access. If it didn't do that, I can't think of many practical uses... – R.. GitHub STOP HELPING ICE Jan 18 '12 at 14:01
  • You could use a mutex without implicit memory barrier, to safely access a resource like an IO device. But never mind, I just wanted to know if that's always the case and apparently it is :-) – Markus Kramer Jan 18 '12 at 14:27

3 Answers3

1

You should work by the book, and let the smart people who implemented the mutex worry about visibility and barriers. The book says a mutex should be held both when reading and when writing.

The CPU can rearrange reads, and does this a lot. It helps reduce the penalty of cache misses, because you start to fetch the data a while before it's actually needed.
So if you read a variable after another CPU wrote it and released the lock, the read may actually be performed before these things happen.
The mutex serves as a memory barrier, preventing this problem (and others).

ugoren
  • 16,023
  • 3
  • 35
  • 65
0

The mutex object should only be read through the g_static_mutex_* functions. If you want to know if you can acquire the mutex you can use this function:

g_static_mutex_trylock 

On the linkage of the identifier, it follows the same rules as with any other C identifier: it depends in which scope it is declared and if some storage class specifier (e. g., static or extern) is specified.

ouah
  • 142,963
  • 15
  • 272
  • 331
0

I guess I found the answer. Gthread is a wrapper around pthread (according to http://redmine.lighttpd.net/boards/3/topics/425) and pthreads seem to implement a memory barrier (http://stackoverflow.com/questions/3208060/does-guarding-a-variable-with-a-pthread-mutex-guarantee-its-also-not-cached) But I'm uncertain if it is necessary to use the mutex read the value.

Markus Kramer
  • 411
  • 5
  • 13