先看一下這篇文章
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);
改進之后就剛剛好