Thread synchronization: mutex

How does mutex work?
  • Only one thread may have the mutex locked at any given time.
  • Threads blocks if the mutex is already owned by another thread.
  • When the mutex is unlocked, the highest-priority thread will unblock and become the new owner of the mutex.
Note: in QNX, On most processors, acquiring a free/unlocked mutex doesn’t require entry to the kernel — the OS/kernel is only used to resolve contention. Therefore, acquisition and rlease of an uncontested critical section or resouce is very quick. The kernel is only involved:
  • to put the waiting thread to a blocked list if the mutex is being held, and
  • to unblock a thread if it is of the highest priority thread in the waiting list, when the mutex is being released.
(default) mutex attributes
  • PTHREAD_PRIO_INHERIT  The priority of the thread, which has locked the mutex, is raised to the highest priority of the threads, which are blocked, waiting on this mutex.
  • PTHREAD_RECURSIVE_DISABLE   any thread that tries to lock an already locked mutex becomes blocked.
Mutex administration
  •  initialize a statically allocated mutex, with the default attributes
    • pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER
  • a normal initialization/destroy of mutex
    •  int pthread_mutex_init(&mutex, &attr); // if attr is NULL, default attributes.
    •  int pthread_mutex_destroy(&mutex)
  • play attribute values
    • pthread_mutexattr_get/set…(&attr, xx);
Using muex
  • Int pthread_mutex_lock(&mutex)  // the thread blocks until it has accquired the mutex.
  • pthread_mutex_timedlock(&mutex, struct timespec *ts_timeout);
  • pthread_mutex_timelock_monotonic(&mutex, struct timespec *ts_timeout)); // not affected by changes to the system time.
  • Int pthread_mutex_unlock(&mutex);
  • Int pthread_mutex_trylock(&mutex); // not block the thread if the mutex is already locked. The return value “EBUSY” means the mutex is already locked.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s