IBM Home Products Consulting Industries News About IBM Search
IBM : developerWorks : Linux library
Common threads: POSIX threads explained, Part 2
The little things called mutexes
Daniel Robbins
President/CEO, Gentoo Technologies, Inc.
August 2000
Contents:
Mutex me!
Comprehension time
Why mutex at all?
Inside threads 1
Inside threads 2
Many mutexes
Using the calls: initialization
Using the calls: locking
Waiting on conditions
Resources
About the author
POSIX threads are a great way to increase the responsiveness and performance of your code.
In this second article of a three-part series, Daniel Robbins shows you how to protect the
integrity of shared data structures in your threaded code by using nifty little things called
mutexes.
Mutex me!
In my previous article, I talked about threaded code that did unusual and unexpected things. Two
threads each incremented a global variable twenty times. The variable was supposed to end up with a
value of 40, but ended up with a value of 21 instead. What happened? The problem occurred because
one thread repeatedly "cancelled out" the increment performed by the other thread. Let's take a look at
some corrected code that uses a mutex to solve the problem:
thread3.c
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
int myglobal;
pthread_mutex_t mymutex=PTHREAD_MUTEX_INITIALIZER;
void *thread_function(void *arg) {
int i,j;
for ( i=0; i<20; i++ ) {
pthread_mutex_lock(&mymutex);
j=myglobal;
j=j+1;
printf(".");
fflush(stdout);
sleep(1);
myglobal=j;
pthread_mutex_unlock(&mymutex);
}
return NULL;
}
int main(void) {
pthread_t mythread;
int i;
if ( pthread_create( &mythread, NULL, thread_function, NULL) ) {
printf("error creating thread.");
abort();
}
for ( i=0; i<20; i++) {
pthread_mutex_lock(&mymutex);
myglobal=myglobal+1;
pthread_mutex_unlock(&mymutex);
printf("o");
fflush(stdout);
sleep(1);
}
developerWorks : linux : Features / Library - Papers
http://www-4.ibm.com/software/developer/library/posix2/index.html (1 of 6) [8/23/2000 11:18:01 AM]