8
Mutual exclusion
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- #define NLOOPS 1000000
- #define MUTEX 1
- #if MUTEX
- pthread_mutex_t mutexcounter;
- #endif
- void *inc( void *vp ) {
- int *cp = (int *) vp;
- int i;
- for ( i = 0; i < NLOOPS; i++ ) {
- #if MUTEX
- pthread_mutex_lock( &mutexcounter );
- #endif
- ++(*cp);
- #if MUTEX
- pthread_mutex_unlock( &mutexcounter );
- #endif
- }
- pthread_exit( 0 );
- }
- void *dec( void *vp ) {
- int *cp = (int *) vp;
- int i;
- for ( i = 0; i < NLOOPS; i++ ) {
- #if MUTEX
- pthread_mutex_lock( &mutexcounter );
- #endif
- --(*cp);
- #if MUTEX
- pthread_mutex_unlock( &mutexcounter );
- #endif
- }
- pthread_exit( 0 );
- }
- int main( int argc, char *argv[] ) {
- pthread_t maker, taker;
- pthread_attr_t attr;
- void *status;
- int counter = 0;
- #if MUTEX
- pthread_mutex_init( &mutexcounter, 0 );
- #endif
- pthread_attr_init( &attr );
- pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
- pthread_create( &maker, &attr, inc, (void *) &counter );
- pthread_create( &taker, &attr, dec, (void *) &counter );
- pthread_attr_destroy( &attr );
- pthread_join( maker, &status );
- pthread_join( taker, &status );
- printf( "counter=%d\n", counter );
- #if MUTEX
- pthread_mutex_destroy( &mutexcounter );
- #endif
- pthread_exit( 0 );
- }
Edit mutex.c and set MUTEX
to 0
. Compile the program and run it:
$ gcc -Wall -lpthread mutex.c -o mutex
$ ./mutex
counter=-3516
$ ./mutex
counter=122812
The expected result is 0.
Edit mutex.c and set MUTEX
to 1
. Compile the program and run it:
$ gcc -Wall -lpthread mutex.c -o mutex
$ ./mutex
counter=0
Now that changing the counter is protected, the result is correct. The program is also slower.
Comments