日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > windows >内容正文

windows

线程之售票系统pthread_mutex,_lock,_unlock

發(fā)布時間:2023/11/30 windows 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 线程之售票系统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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。