linux下使用线程锁互斥访问资源
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
作 者:fengbohello
个人网站:http://www.fengbohello.top/
E-mail : fengbohello@foxmail.com
欢迎转载,转载请注明作者和出处。
因作者水平有限,不免出现遗漏和错误。希望热心的同学能够帮我指出来,我会尽快修改。愿大家共同进步,阿里嘎多~
标签:
线程锁
, pthread_mutex
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?