当前位置:
首页 >
线程之售票系统pthread_mutex,_lock,_unlock
发布时间:2023/11/30
60
豆豆
生活随笔
收集整理的这篇文章主要介绍了
线程之售票系统pthread_mutex,_lock,_unlock
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
先看一下这篇文章
https://blog.csdn.net/csdn_kou/article/details/81148268
四个人同时买票票,引出线程
#include "head.h" int ticket = 100; void * route(void *arg) {char *id = (char *)arg;while(1){if(ticket>0){usleep(1000);printf("%s sells:%d\n",id,ticket);ticket--;}else{break;}} }int main() {key_t key = ftok (".",1);pthread_t t1,t2,t3,t4;pthread_create(&t1,NULL,route,"thread 1");pthread_create(&t2,NULL,route,"thread 2");pthread_create(&t3,NULL,route,"thread 3");pthread_create(&t4,NULL,route,"thread 4");pthread_join(t1,NULL);pthread_join(t2,NULL);pthread_join(t3,NULL);pthread_join(t4,NULL);return 0; }
四个人抢票,争的票都卖出负数了,这在实际中是不可以的
改进:引入互斥量加锁和解锁概念
#include "head.h" #include <pthread.h> #include <unistd.h>int ticket = 100; pthread_mutex_t mutex;void * route(void *arg) {char *id = (char *)arg;while(1){pthread_mutex_lock(&mutex);if(ticket>0){usleep(1000);printf("%s sells:%d\n",id,ticket);ticket--;pthread_mutex_unlock(&mutex);}else{break;}}}int main() {key_t key = ftok (".",1);pthread_t t1,t2,t3,t4;pthread_create(&t1,NULL,route,"thread 1");pthread_create(&t2,NULL,route,"thread 2");pthread_create(&t3,NULL,route,"thread 3");pthread_create(&t4,NULL,route,"thread 4");pthread_join(t1,NULL);pthread_join(t2,NULL);pthread_join(t3,NULL);pthread_join(t4,NULL);return 0; }
这是我们发现票是卖的刚刚好,可是卡在那里了。
因为卖完最后一张票,没有进入if语句,在else语句中没有解锁,特别注意的是,用一次
pthread_mutex_lock(&mutex);
就必须在任何有可能退出的地方进行解锁
pthread_mutex_unlock(&mutex);
改进之后就刚刚好
总结
以上是生活随笔为你收集整理的线程之售票系统pthread_mutex,_lock,_unlock的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: segmentfault的右上角的小铃铛
- 下一篇: ySQL挑战搭建一个简易的成绩管理系统的