公交⻋上,司机和售票员的活动分别是 a司机:启动⻋辆、行⻋、到站停⻋ a售票员:关⻋⻔、售票、开⻋⻔ 试用信号量和P、V操作描述汽⻋不断到站、停 ⻋、行驶过程并实现同步。使用c语言
时间: 2023-12-22 07:05:22 浏览: 122
用html5和javascript实现进程同步模拟——司机售票员问题
4星 · 用户满意度95%
这是一个经典的信号量同步问题,可以通过如下代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define NUM_STATIONS 5
sem_t sem_driver, sem_conductor;
void* driver(void* arg) {
int station = (int)arg;
while (1) {
printf("Driver #%d arrives at station %d\n", pthread_self(), station);
sem_wait(&sem_driver);
printf("Driver #%d starts the bus at station %d\n", pthread_self(), station);
sleep(1);
sem_post(&sem_conductor);
}
return NULL;
}
void* conductor(void* arg) {
int station = (int)arg;
while (1) {
printf("Conductor #%d arrives at station %d\n", pthread_self(), station);
sem_wait(&sem_conductor);
printf("Conductor #%d opens the door at station %d\n", pthread_self(), station);
sleep(1);
sem_post(&sem_driver);
printf("Conductor #%d closes the door at station %d\n", pthread_self(), station);
sleep(1);
}
return NULL;
}
int main() {
pthread_t driver_threads[NUM_STATIONS], conductor_threads[NUM_STATIONS];
sem_init(&sem_driver, 0, 1);
sem_init(&sem_conductor, 0, 0);
for (int i = 0; i < NUM_STATIONS; ++i) {
pthread_create(&driver_threads[i], NULL, driver, (void*)i);
pthread_create(&conductor_threads[i], NULL, conductor, (void*)i);
}
for (int i = 0; i < NUM_STATIONS; ++i) {
pthread_join(driver_threads[i], NULL);
pthread_join(conductor_threads[i], NULL);
}
sem_destroy(&sem_driver);
sem_destroy(&sem_conductor);
return 0;
}
```
在主函数中,我们创建5个司机线程和5个售票员线程,分别代表5个公交车站。每个线程的参数表示它所在的车站编号。在每个司机线程中,我们使用 `sem_wait` 语句等待售票员开门,然后启动公交车行驶。在每个售票员线程中,我们使用 `sem_wait` 语句等待司机关闭车门,然后售票并开门。在两个线程的交替执行中,使用信号量来保证同步。
阅读全文