线程之售票系统pthread_mutex,_lock,_unlock
生活随笔
收集整理的這篇文章主要介紹了
线程之售票系统pthread_mutex,_lock,_unlock
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
先看一下這篇文章
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; }
四個人搶票,爭的票都賣出負數(shù)了,這在實際中是不可以的
改進:引入互斥量加鎖和解鎖概念
#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; }
這是我們發(fā)現(xiàn)票是賣的剛剛好,可是卡在那里了。
因為賣完最后一張票,沒有進入if語句,在else語句中沒有解鎖,特別注意的是,用一次
pthread_mutex_lock(&mutex);
就必須在任何有可能退出的地方進行解鎖
pthread_mutex_unlock(&mutex);
改進之后就剛剛好
總結(jié)
以上是生活随笔為你收集整理的线程之售票系统pthread_mutex,_lock,_unlock的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: segmentfault的右上角的小铃铛
- 下一篇: 律师岳家军第二季剧情介绍