linux 线程 互斥锁
互斥量(锁):
为避免线程更新共享变量时出现问题,可以使用互斥量(mutex 是 mutual exclusion 的缩写)来确保同时仅有一个线程可以访问某项共享资源。可以使用互斥量来保证对任意共享资源的原子访问。
互斥量有两种状态:已锁定(locked) 和 未锁定(unlocked)。任何时候,至多只有一个线程可以锁定该互斥量。试图对已经锁定的某一互斥量再次加锁,将可能阻塞线程或者报错失败,具体取决于加锁时使用的方法。
一旦线程锁定互斥量,随即成为该互斥量的所有者,只有所有者才能给互斥量解锁。一般情况下,对每一个共享资源(可能由多个相关变量组成)会使用不同的互斥量,每一线程在访问同一资源时将采用如下协议:
⚪针对共享资源锁定互斥量
⚪访问共享资源
⚪对互斥量解锁
如果多个线程试图执行这一块代码(一个临界区),事实上只有一个线程能够持有该互斥量(其他线程将遭到阻塞),即同时只有一个线程能够进入这段代码区域,如图:
1 /* 2 互斥量(锁)的类型 pthread_mutex_t 3 int pthread_mutex_init(pthread_mutex_t * restrict mutex, const pthread_mutexattr_t * restrict attr); 4 - 初始化互斥量 5 - 参数: 6 - mutex: 需要初始化的的互斥量变量 7 - attr: 互斥量相关的属性, NULL 8 - restrict: C语言的修饰符, 被修饰的指针, 不能由另外的一个指针进行操作 9 pthread_mutex_t *restrict mutex = XXX; 10 pthread_mutex_t * mutex1 = mutex;//报错 11 int pthread_mutex_destroy(pthread_mutex_t * mutex); 12 - 释放互斥量的资源 13 int pthread_mutex_lock(pthread_mutex_t * mutex); 14 - 加锁, 阻塞的, 如果有一个线程加锁了, 那么其他的线程只能阻塞等待 15 int pthread_mutex_trylock(pthread_mutex_t * mutex); 16 - 尝试加锁,如果加锁失败, 不会阻塞, 会直接返回 17 int pthread_mutex_unlock(pthread_mutex_t * mutex); 18 - 解锁 19 */ 20 #include <stdio.h> 21 #include <pthread.h> 22 #include <unistd.h> 23 int tickets = 500;//全局变量, 所有的线程都共享这一份资源 24 //创建一个互斥量 25 pthread_mutex_t mutex;//全局变量 26 void * sellticket(void * arg) 27 { 28 //A B C A先进 然后加锁 执行while 解锁 B C A都有机会执行代码区 有解锁后才可以进行执行 29 //卖票 30 while(1) 31 { 32 //加锁 33 pthread_mutex_lock(&mutex); 34 if(tickets > 0) 35 { 36 usleep(6000); 37 printf("%ld 正在卖第 %d 张门票\n",pthread_self(),tickets); 38 tickets--; 39 } 40 else 41 { 42 // = 0 解锁 43 pthread_mutex_unlock(&mutex); 44 break; 45 } 46 pthread_mutex_unlock(&mutex); 47 } 48 return NULL; 49 } 50 int main() 51 { 52 //初始化 53 pthread_mutex_init(&mutex, NULL); 54 //创建3个子线程 55 pthread_t tid1,tid2,tid3; 56 pthread_create(&tid1, NULL, sellticket, NULL); 57 pthread_create(&tid2, NULL, sellticket, NULL); 58 pthread_create(&tid3, NULL, sellticket, NULL); 59 //回收子线程的资源, 阻塞 60 pthread_join(tid1,NULL); 61 pthread_join(tid2,NULL); 62 pthread_join(tid3,NULL); 63 pthread_exit(NULL);//退出主线程 64 //释放互斥量资源 65 pthread_mutex_destroy(&mutex); 66 return 0; 67 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)