Take the 2-minute tour ×

I have a global variable flag, a function this(), and a function that(). Now, main(), this() and that() all have occasions where they need to read and/or write flag. To properly use a mutex I would need to:

  1. declare a pthread_mutex_t and initialize it.
  2. create threads for this() and that() and pthread_join() them because I want main() to wait on this() and that() to finish before exiting.
  3. anywhere in the code, be it main(), this(), or that(), where flag is being read or written, call pthread_mutex_lock() then [read/write] flag then call pthread_mutex_unlock()

Is that correct?

I don't plan on doing this but if I want to check flag in an infinite loop in main() like this:

    while(flag != value)

Where would you lock() and unlock() the mutex and would the other threads get a chance to access flag with main() being constantly all over it like that?

share|improve this question
You'd want a pthread condition for that last loop. –  Ben Jackson Mar 20 '13 at 22:30
Use pthread objects for what they are intended for. A mutex guards access to something (or things), while a condition variable is used to signal change in a predicate to one or more potential interested parties. Properly used in concert, the tasks you spell out are both elegant, and fairly trivial. –  WhozCraig Mar 20 '13 at 22:32
add comment

1 Answer

up vote 1 down vote accepted

1 - 2 - 3 - correct.

Now, if your write that loop, then

  • as a consequence of 3, the main thread will hold the lock, and other threads won't be able to acquire the lock, so in effect, you created an infinite loop.
  • if you don't lock, then it might not work, it depends on the CPU architecture (first of all, flag needs to be atomically updateable, and other cores need to see those changes. not all architectures guarantee this). Even if it works, it's still a busy wait loop, and shouldn't be used.

As Ben pointed out in his comment, you want to use condition variables for signaling (note: Pthread and wait conditions)

Where would you lock() and unlock() the mutex

As a thumb of rule, to minimize the contention, hold the lock as short as possible. This could be as simple as lock+read+unlock, but if the following sequence of operations depend on the fact that the flag shouldn't be changed, then keep the lock as long as needed.

share|improve this answer
Thank you. That is more or less what I thought, just wanted to make sure I had the gist of it before making my first foray into mutexes. I read and re-read the man pages and looked at several examples from various sources and at the end of it I still wasn't sure I had a handle on it. @WhozCraig - It's heavy stuff for a novice, self-taught guy like me ;) –  JB0x2D1 Mar 20 '13 at 23:15
add comment

Your Answer


