home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 3: Developer Tools / Linux Cubed Series 3 - Developer Tools.iso / devel / lang / c / pthd-0.000 / pthd-0 / pthd-0.7 / src_mutex / mutex.c.2 < prev    next >
Encoding:
Text File  |  1995-08-16  |  1.6 KB  |  79 lines

  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <pthread.h>
  4. #include "error_msg.h"
  5.  
  6. void lock_mu( pthread_mutex_t *mu )
  7. {
  8.    int st;
  9.  
  10.    st = pthread_mutex_lock( mu );
  11.    CHECK(st, "pthread_mutex_lock()");
  12.    printf("\t\t>Child locked mutex\n");
  13.  
  14.    st = pthread_mutex_unlock( mu );
  15.    CHECK(st, "pthread_mutex_unlock()");
  16.    printf("\t\t>Child has unlocked mutex\n");
  17.  
  18.    pthread_exit( (void *) SUCCESS );
  19. }
  20.  
  21. void
  22. init_mu( pthread_mutex_t *mu )
  23. {
  24.    int st;
  25.  
  26.    st = pthread_mutex_init( mu, NULL );
  27.    CHECK( st, "pthread_mutex_init()");
  28. }
  29.  
  30. void
  31. destroy_mu( pthread_mutex_t *mu )
  32. {
  33.    int st;
  34.  
  35.    st = pthread_mutex_destroy( mu );
  36.    CHECK(st, "pthread_mutex_destroy()");
  37. }
  38.  
  39. static pthread_mutex_t mutex;
  40. static pthread_t th;
  41.  
  42. int 
  43. main( int argc, char *argv[] )
  44. {
  45.    int st;
  46.  
  47.    init_mu( &mutex );
  48.  
  49.    /*
  50.     *  --  Now, lock the mutex, and create a second thread.  The second
  51.     *      thread will attempt to lock the same mutex, and block until
  52.     *      the mutex is released.
  53.     */
  54.    st = pthread_mutex_lock( &mutex );
  55.    CHECK(st, "pthread_mutex_lock()");
  56.  
  57.    printf("\t\t>Main has locked the mutex\n");
  58.  
  59.    /*
  60.     *  --  This is the second thread that should block when it attempts to
  61.     *      lock mu.
  62.     */
  63.    st = pthread_create( &th, NULL, (thread_proc_t)lock_mu, &mutex );
  64.    CHECK(st, "pthread_create()");
  65.    pthread_yield( NULL );
  66.  
  67.    /*
  68.     *  --  Unlock the mutex
  69.     */
  70.    st = pthread_mutex_unlock( &mutex );
  71.    CHECK(st, "pthread_mutex_unlock()");
  72.  
  73.    printf("\t\t>Main has unlocked the mutex\n");
  74.    pthread_yield( NULL );
  75.  
  76.    destroy_mu( &mutex );
  77.    return( EXIT_SUCCESS );
  78. }
  79.