0

As a beginner to threads, I have a slight difficulty in understanding how the logic of mutex works. Need help in understanding how multi-threading works in the following snippet and what would be the output of x for every foo() call:

foo()
{
  static int x;
  X_lock();     //locking
  x++;
  X_unlock;     //unlocking
  return x;
}

And what's the basic difference between a semaphore and mutex? A simple example would be nice.

LPs
  • 16,045
  • 8
  • 30
  • 61
Vin-
  • 19
  • 4
  • Please revise your question. What have you tried? What resources have you read? What exactly don't you understand. Please don't expect people on SO to do your homework – Ishay Peled Jun 20 '16 at 07:44
  • Take a look at [this SO Q&A](http://stackoverflow.com/questions/2065747/pthreads-mutex-vs-semaphore) – LPs Jun 20 '16 at 07:58
  • 1
    If executed by multiple threads concurrently, your example exhibits undefined behavior due to non-atomic, non-readonly access to `x`, since the last access in `return x;` is not protected by the mutex. – EOF Jun 20 '16 at 08:31

1 Answers1

1

Some times threads needs to use the same resource and that can invoke unidentified behavior. For example addition is not atomic operation and therefore can cause this problem. So there is need for some kind of barrier between different threads, only one thread can pass that barrier, and others have to wait for that thread to finish, after one thread finishes, next go trough barrier and others have to wait for thread to finish.

This is one example of race condition and MUTEX (mutual exclusion) is used for this. How does mutex work? First you must initialize mutex in main function:

pthread_mutex_init(&lock, NULL).

Variable pthread_mutex_t lock; is global, so every thread can access it. Afterwards, one thread will lock mutex:

pthread_mutex_lock(&lock);

And now, next thread comes to this same point, to this line of code I just wrote, and can't get passed trough it. So every other thread have to wait at this barrier - this line of code, until first thread unlock mutex:

pthread_mutex_unlock(&lock);

Then depending which thread get processor time from OS will pass trough barrier and same thing repeats all over again.

Mutexes are very important concept to understand. As for semaphores, they are used for same thing, thread synchronization, here is excellent article covering this topic.

Aleksandar Makragić
  • 1,957
  • 17
  • 32