当前位置: 首页> 财经> 金融 > Linux——互斥与同步练习

Linux——互斥与同步练习

时间:2025/8/9 8:35:29来源:https://blog.csdn.net/m0_71703182/article/details/140117971 浏览次数:0次

用多线程程序设计一个火车票售票系统,
要求至少有两个售票窗口,每个售票窗口
不能重复买票,将100张车票均匀的从两个
窗口卖出即可。

./a.out 
窗口1 卖出车票 1
窗口2 卖出车票 2
窗口1 卖出车票 3
窗口2 卖出车票 4
.....


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
int num=100;
int WIN[2]={1,1};
sem_t sem_WIN;
pthread_mutex_t mutex;
pthread_mutex_t mutex_win;
int get_win()
{sem_wait(&sem_WIN);int i = 0 ;for(i = 0 ;i<2;i++){pthread_mutex_lock(&mutex_win);if(1==WIN[i]){WIN[i] = 0 ;pthread_mutex_unlock(&mutex_win);return i;}else {pthread_mutex_unlock(&mutex_win);}}return -1;}
void relese_win(int id)
{pthread_mutex_lock(&mutex_win);WIN[id]=1;pthread_mutex_unlock(&mutex_win);sem_post(&sem_WIN);
}
void* th(void* arg)
{while(1){pthread_mutex_lock(&mutex);if(num>0){int n = num--;pthread_mutex_unlock(&mutex);int id = get_win();printf("win %d, ticket:%d tid:%lu\n",id+1 ,n,pthread_self());usleep(1000*100);relese_win(id);}else{pthread_mutex_unlock(&mutex);break;}}return NULL;}
int main(int argc, char *argv[])
{pthread_t tid1,tid2;pthread_mutex_init(&mutex,NULL);pthread_mutex_init(&mutex_win,NULL);sem_init(&sem_WIN,0,2);pthread_create(&tid1,NULL,th,NULL);pthread_create(&tid2,NULL,th,NULL);pthread_join(tid1,NULL);pthread_join(tid2,NULL);sem_destroy(&sem_WIN);pthread_mutex_destroy(&mutex);pthread_mutex_destroy(&mutex_win);return 0;
}

启动三个线程,th1输出a,th2输出b,th3输出c。输出
abcabcabcabc。 10个abc

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
#include<string.h>
#include<semaphore.h>
sem_t sem1,sem2,sem3;
void *th1(void*arg)
{int i=10;while(i--){sem_wait(&sem1);printf("a");fflush(stdout);sem_post(&sem2);}return NULL;}void *th2(void *arg)
{int i=10;while(i--){sem_wait(&sem2);printf("b");sleep(1);fflush(stdout);sem_post(&sem3);}return NULL;}
void *th3(void *arg)
{int i=10;while(i--){sem_wait(&sem3);printf("c");sleep(1);fflush(stdout);sem_post(&sem1);}return NULL;}int main(int argc, const char *argv[])
{pthread_t tid1,tid2,tid3;sem_init(&sem1,0,1);sem_init(&sem2,0,0);sem_init(&sem3,0,0);pthread_create(&tid1,NULL,th1,NULL);pthread_create(&tid2,NULL,th2,NULL);pthread_create(&tid3,NULL,th3,NULL);pthread_join(tid1,NULL);pthread_join(tid2,NULL);pthread_join(tid3,NULL);sem_destroy(&sem1);sem_destroy(&sem2);sem_destroy(&sem3);return 0;	}

关键字:Linux——互斥与同步练习

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: