求一份代码,操作系统题目
用进程同步方法解决售票员与乘客问题
有代码就好!价格有待商议
#include<iostream>
using namespace std;
int spy=1, sj=0; //信号量的定义,spy是售票员的私有信号量,sj是司机的私有信号量。
#define SIZE 5 //定义车上最多能坐的人数。
int n = SIZE;
char ck; //乘客上下车的操作变量。
int p1(); //司机的操作流程。
int p2(); //售票员的操作流程。
int main()
{
cout << "键入a表示乘客上车,键入d表示乘客下车." << endl;
cout << "键入s表示注销进程." << endl;
cout << "键入f表示乘客上下车过程结束." << endl << endl << endl;
p1();
return 0;
}
int p1() //司机的执行过程
{
sj--;//相当于p操作。
if (sj == 0)
{
cout << "汽车启动准备离站......" << endl;
cout << "汽车运行中......" << endl;
cout << "汽车到站!" << endl;
cout << "汽车停!" << endl;
spy++;//相当于v操作。
}
else sj++;
p2();
return 0;
}
int p2() //售票员的执行过程
{
spy--;//相当于p操作。
if (spy==0)
{
cout << "售票员打开车门......" << endl;
cout << "请进行乘客上下车操作!" << endl;
while (1)
{
cin >> ck;
if ((ck == 'a') && (n > 0)) {n--;cout << "上一个乘客." << endl;continue;};
if ((ck == 'd') && (n < SIZE)) {n++;cout << "下一个乘客." << endl;continue;};
if (ck == 'f') {break;};
if (ck == 's') {return 0;};
if (n <= 0) {cout << "车上座位已满,不能再上乘客了!" << endl;continue;};
if (n >= SIZE) {cout << "车上乘客已经都下完了!" << endl;continue;};
}
cout << "现在关闭车门!" << endl;
}
sj++; //相当于v操作
p1();
return 0;
}
看下这篇实例【操作系统售票员与乘客】,链接:https://www.codenong.com/cs106712436/
【推荐理由,类型相似,讲解详细,注解清晰】
from threading import Semaphore
ticket_sem = Semaphore(1) # 用于控制售票员的访问
customer_sem = Semaphore(0) # 用于控制乘客的访问
def ticket_seller():
while True:
ticket_sem.acquire()
# 卖票
customer_sem.release()
def customer():
while True:
customer_sem.acquire()
# 拿票
ticket_sem.release()
在解决售票员与乘客问题时,常用的进程同步方法之一是使用互斥锁,参考:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define NUM_TICKETS 100
int tickets = NUM_TICKETS;
pthread_mutex_t mutex;
void *seller(void *arg)
{
while (tickets > 0)
{
pthread_mutex_lock(&mutex);
if (tickets > 0)
{
printf("Seller: ticket %d sold\n", tickets);
tickets--;
}
pthread_mutex_unlock(&mutex);
}
return NULL;
}
void *buyer(void *arg)
{
while (tickets > 0)
{
pthread_mutex_lock(&mutex);
if (tickets > 0)
{
printf("Buyer: ticket %d bought\n", tickets);
tickets--;
}
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main(int argc, char *argv[])
{
pthread_t tid1, tid2;
pthread_mutex_init(&mutex, NULL);
pthread_create(&tid1, NULL, seller, NULL);
pthread_create(&tid2, NULL, buyer, NULL);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
pthread_mutex_destroy(&mutex);
return 0;
}