Locks
The mutual exclusion is a very important utility needed in multithreaded programs. You will study locks in this lesson, that serve this purpose.
We'll cover the following...
Beyond thread creation and join, probably the next most useful set of functions provided by the POSIX threads library are those for providing mutual exclusion to a critical section via locks. The most basic pair of routines to use for this purpose is provided by the following:
int pthread_mutex_lock(pthread_mutex_t *mutex);int pthread_mutex_unlock(pthread_mutex_t *mutex);
Lock and unlock routines
The routines should be easy to understand and use. When you have a region of code that is a critical section and thus needs to be protected to ensure correct operation, locks are quite useful. You can probably imagine what the code looks like:
pthread_mutex_t lock;pthread_mutex_lock(&lock);x = x + 1; // or whatever your critical section ispthread_mutex_unlock(&lock);
The intent of the code is as follows: if no other thread holds the lock when pthread_mutex_lock()
is called, the thread ...