案例1:错误演示
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
void *tick(void *arg)
{
static int num = 100;
while (num > 0)
{
num--;
sleep(0.1);
printf("线程%ld销售了一张票,还剩%d张\n", pthread_self(), num);
}
return NULL;
}
int main(int argc, char const *argv[])
{
pthread_t p1, p2, p3, p4;
pthread_create(&p1, NULL, tick, NULL);
pthread_create(&p2, NULL, tick, NULL);
pthread_create(&p3, NULL, tick, NULL);
pthread_create(&p4, NULL, tick, NULL);
pthread_join(p1, NULL);
pthread_join(p2, NULL);
pthread_join(p3, NULL);
pthread_join(p4, NULL);
return 0;
}
案例2:加锁后
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
int ticket = 100;
pthread_mutex_t lock;
// pthread_cond_t cond;
void *sale(void *name)
{
while(ticket > 0)
{
pthread_mutex_lock(&lock);
if(ticket <= 0)
{
pthread_mutex_unlock(&lock);
break;
}
ticket--;
sleep(0.5);
printf("%s售卖了一张船票,还剩%d张船票\n",(char *)name,ticket);
pthread_mutex_unlock(&lock);
}
return NULL;
}
int main(int argc, char const *argv[])
{
pthread_mutex_init(&lock,NULL);//初始化
pthread_t tid1,tid2,tid3,tid4;
pthread_create(&tid1,NULL,sale,"一号窗口");
pthread_create(&tid2,NULL,sale,"二号窗口");
pthread_create(&tid3,NULL,sale,"三号窗口");
pthread_create(&tid3,NULL,sale,"四号窗口");
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_join(tid3,NULL);
pthread_join(tid4,NULL);
pthread_mutex_destroy(&lock);
return 0;
}
文章来源:https://blog.csdn.net/aisheisadas/article/details/134976728
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:chenni525@qq.com进行投诉反馈,一经查实,立即删除!