linux使用线程锁访问互斥资源:
1、线程锁的创建
pthread_mutex_t g_Mutex;
2、完整代码如下
1 #include <stdio.h> 2 #include <string.h> 3 #include <pthread.h> 4 #include <stdlib.h> 5 #include <unistd.h> 6 #include <errno.h> 7 #include <signal.h> 8 9 #define READ_TIME 20000 10 #define WRITE_TIME 30000 11 12 pthread_mutex_t g_Mutex; 13 int g_iX = 0; 14 int g_rwok = 0; 15 16 bool bExit = false; 17 18 void sig(int signal) 19 { 20 bExit = true; 21 } 22 23 /* writer pthread, write per 30000 us */ 24 void * writer(void * arg) 25 { 26 while(1) 27 { 28 if(true == bExit) 29 { 30 g_rwok++; 31 break; 32 } 33 if(EBUSY != pthread_mutex_trylock(&g_Mutex)) 34 { 35 printf("\033[0;32mwriter : lock, write begin\033[0m\n"); 36 g_iX = 1; 37 usleep(WRITE_TIME); 38 pthread_mutex_unlock(&g_Mutex); 39 printf("\033[0;32mwriter : write ok, unlock\033[0m\n"); 40 } 41 else 42 { 43 printf("\033[0;32mwriter : \033[0;31mbusy , can not write\033[0m\n"); 44 } 45 usleep(WRITE_TIME); 46 } 47 48 return NULL; 49 } 50 51 /* reader pthread, read per 20000 us */ 52 void * reader(void * arg) 53 { 54 while(1) 55 { 56 if(true == bExit) 57 { 58 g_rwok++; 59 break; 60 } 61 if(EBUSY != pthread_mutex_trylock(&g_Mutex)) 62 { 63 printf("\033[0;33mreader : lock\033[0m\n"); 64 g_iX = 0; 65 usleep(READ_TIME); 66 pthread_mutex_unlock(&g_Mutex); 67 printf("\033[0;33mreader : unlock , read ok\033[0m\n"); 68 } 69 else 70 { 71 printf("\033[0;33mreader : \033[0;31mbusy , can not read\033[0m\n"); 72 } 73 usleep(READ_TIME); 74 } 75 76 return NULL; 77 } 78 79 int main(int argc, char *argv[]) 80 { 81 signal(SIGINT, sig); 82 memset(&g_Mutex, sizeof(g_Mutex), 0); 83 pthread_mutex_init(&g_Mutex, NULL); 84 85 pthread_t preader, pwriter; 86 pthread_create(&preader, NULL, reader, NULL); 87 pthread_create(&pwriter, NULL, writer, NULL); 88 while(1) 89 { 90 if(true == bExit && 2 == g_rwok) 91 { 92 break; 93 } 94 usleep(100000); 95 } 96 pthread_mutex_destroy(&g_Mutex); 97 printf("\033[0;33mdestroy mutex\033[0m\n"); 98 99 return 0; 100 }
3、运行结果如下
reader : lock writer : busy , can not write reader : unlock , read ok writer : lock, write begin reader : busy , can not read writer : write ok, unlock reader : lock reader : unlock , read ok writer : lock, write begin reader : busy , can not read writer : write ok, unlock
本文转自郝峰波博客园博客,原文链接:http://www.cnblogs.com/fengbohello/p/4112679.html,如需转载请自行联系原作者