看下简单的例子:
1 #include <pthread.h> 2 #include <stdlib.h> 3 #include <stdio.h> 4 #include <unistd.h> 5 #include <string.h> 6 7 pthread_mutex_t glock = PTHREAD_MUTEX_INITIALIZER; 8 struct foo 9 { 10 int f_count; 11 pthread_mutex_t f_lock; 12 }; 13 struct foo* AllocFoo() 14 { 15 foo* lpFoo = (foo*)malloc(sizeof(struct foo)); 16 if(NULL != lpFoo) 17 { 18 lpFoo->f_count = 1; 19 if(0 != pthread_mutex_init(&lpFoo->f_lock,NULL)) 20 { 21 printf("pthread_mutex_init error. "); 22 free(lpFoo); 23 return NULL; 24 } 25 } 26 printf("Alloc a Foo. "); 27 return lpFoo; 28 } 29 30 bool DestoryFoo(foo* apFoo) 31 { 32 pthread_mutex_lock(&apFoo->f_lock); 33 if(--apFoo->f_count == 0) 34 { 35 printf("in DestoryFoo: f_coount:%d. ",apFoo->f_count); 36 pthread_mutex_unlock(&apFoo->f_lock); 37 pthread_mutex_destroy(&apFoo->f_lock); 38 free(apFoo); 39 printf("Destroy foo. "); 40 return true; 41 } 42 else 43 { 44 printf("in DestoryFoo: f_coount:%d. ",apFoo->f_count); 45 pthread_mutex_unlock(&apFoo->f_lock); 46 return false; 47 } 48 } 49 50 void HoldFoo(foo* apFoo) 51 { 52 pthread_mutex_lock(&apFoo->f_lock); 53 ++apFoo->f_count; 54 printf("in HoldFoo f_coount:%d. ",apFoo->f_count); 55 pthread_mutex_unlock(&apFoo->f_lock); 56 } 57 58 void PrintTids(const char* s); 59 60 void* ThreadFun(void* Arg) 61 { 62 PrintTids(""); 63 foo* lpFoo = (foo*)Arg; 64 for(int i=0;i<5;++i) 65 { 66 //pthread_mutex_lock(&glock); 67 HoldFoo(lpFoo); 68 //pthread_mutex_unlock(&glock); 69 } 70 return NULL; 71 } 72 void PrintTids(const char* s) 73 { 74 pid_t lPid = getpid(); 75 pthread_t lTid = pthread_self(); 76 printf("%s pid:%u,tid:(0x%x). ",s,(unsigned int)lPid, (unsigned int)lTid); 77 } 78 int main() 79 { 80 foo* lpFoo = AllocFoo(); 81 pthread_t lTid1; 82 int lErr = pthread_create(&lTid1,NULL,ThreadFun,lpFoo); 83 if(0 != lErr) 84 { 85 exit(1); 86 } 87 printf("main thread"); 88 89 pthread_t lTid2; 90 lErr = pthread_create(&lTid2,NULL,ThreadFun,lpFoo); 91 if(0 != lErr) 92 { 93 exit(1); 94 } 95 //HoldFoo(lpFoo); 96 void* lTret; 97 lErr = pthread_join(lTid1,&lTret); 98 if(0 != lErr) 99 { 100 printf("can't join thread1. "); 101 } 102 lErr = pthread_join(lTid2,&lTret); 103 if(0 != lErr) 104 { 105 printf("can't join thread1. "); 106 } 107 108 bool lIsDestory = false; 109 do 110 { 111 lIsDestory = DestoryFoo(lpFoo); 112 }while(!lIsDestory); 113 }
输出: