locked_vs_unlocked3.c revision b32f58018498ea2225959b0ba11c18f0c433deef
1 2/* Needed for older glibcs (2.3 and older, at least) who don't 3 otherwise "know" about pthread_rwlock_anything or about 4 PTHREAD_MUTEX_RECURSIVE (amongst things). */ 5#define _GNU_SOURCE 1 6 7#include <pthread.h> 8#include <stdio.h> 9#include <stdlib.h> 10#include <assert.h> 11#include <unistd.h> 12 13/* Test of the mechanism for showing all locks held by a thread. This 14 is like locked_vs_unlocked.c, except that it uses a recursively 15 lockable lock, and one thread holds the lock more than once. Point 16 is to check that the lock showing mechanism shows the 17 lock-number-of-times-held count. */ 18 19pthread_mutex_t mx; 20 21int x = 0; 22 23void* child_fn1 ( void* arg ) 24{ 25 int r; 26 r= pthread_mutex_lock(&mx); assert(!r); 27 r= pthread_mutex_lock(&mx); assert(!r); 28 x = 1; 29 r= pthread_mutex_unlock(&mx); assert(!r); 30 r= pthread_mutex_unlock(&mx); assert(!r); 31 sleep(1); 32 return NULL; 33} 34 35void* child_fn2 ( void* arg ) 36{ 37 sleep(1); 38 x = 1; 39 return NULL; 40} 41 42int main ( int argc, char** argv ) 43{ 44 int r; 45 pthread_t child1, child2; 46 pthread_mutexattr_t attr; 47 r = pthread_mutexattr_init( &attr ); 48 assert(!r); 49 r = pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE ); 50 assert(!r); 51 r= pthread_mutex_init(&mx, &attr); assert(!r); 52 53 r= pthread_create(&child2, NULL, child_fn2, NULL); assert(!r); 54 r= pthread_create(&child1, NULL, child_fn1, NULL); assert(!r); 55 56 r= pthread_join(child1, NULL); assert(!r); 57 r= pthread_join(child2, NULL); assert(!r); 58 59 r= pthread_mutex_destroy(&mx); assert(!r); 60 61 return 0; 62} 63