先看一下这篇文章
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);
改进之后就刚刚好