7

Mutual exclusion

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #include <pthread.h>
  5.  
  6. #define NLOOPS      1000000
  7.  
  8. #define MUTEX 1
  9.  
  10. #if MUTEX
  11. pthread_mutex_t mutexcounter;
  12. #endif
  13.  
  14. void *inc( void *vp ) {
  15.     int *cp = (int *) vp;
  16.     int i;
  17.  
  18.     for ( i = 0; i < NLOOPS; i++ ) {
  19. #if MUTEX
  20.         pthread_mutex_lock( &mutexcounter );
  21. #endif
  22.         ++(*cp);
  23. #if MUTEX
  24.         pthread_mutex_unlock( &mutexcounter );
  25. #endif
  26.     }
  27.  
  28.     pthread_exit( 0 );
  29. }
  30.  
  31. void *dec( void *vp ) {
  32.     int *cp = (int *) vp;
  33.     int i;
  34.  
  35.     for ( i = 0; i < NLOOPS; i++ ) {
  36. #if MUTEX
  37.         pthread_mutex_lock( &mutexcounter );
  38. #endif
  39.         --(*cp);
  40. #if MUTEX
  41.         pthread_mutex_unlock( &mutexcounter );
  42. #endif
  43.     }
  44.     pthread_exit( 0 );
  45. }
  46.  
  47. int main( int argc, char *argv[] ) {
  48.     pthread_t maker, taker;
  49.     pthread_attr_t attr;
  50.  
  51.     void *status;
  52.  
  53.     int counter = 0;
  54.  
  55. #if MUTEX
  56.     pthread_mutex_init( &mutexcounter, 0 );
  57. #endif
  58.  
  59.     pthread_attr_init( &attr );
  60.     pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
  61.  
  62.     pthread_create( &maker, &attr, inc, (void *) &counter );
  63.     pthread_create( &taker, &attr, dec, (void *) &counter );
  64.  
  65.     pthread_attr_destroy( &attr );
  66.  
  67.     pthread_join( maker, &status );
  68.     pthread_join( taker, &status );
  69.  
  70.     printf( "counter=%d\n", counter );
  71.  
  72. #if MUTEX
  73.     pthread_mutex_destroy( &mutexcounter );
  74. #endif
  75.  
  76.     pthread_exit( 0 );
  77. }

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

Your comment:
[p] [b] [i] [u] [s] [quote] [pre] [br] [code] [url] [email] strip help 2000

Enter a maximum of 2000 characters.
Improve the presentation of your text with the following formatting tags:
[p]paragraph[/p], [b]bold[/b], [i]italics[/i], [u]underline[/u], [s]strike[/s], [quote]citation[/quote], [pre]as is[/pre], [br]line break,
[url]http://www.izend.org[/url], [url=http://www.izend.org]site[/url], [email]izend@izend.org[/email], [email=izend@izend.org]izend[/email],
[code]command[/code], [code=language]source code in c, java, php, html, javascript, xml, css, sql, bash, dos, make, etc.[/code].