用c语言结构体编写孔融让梨程序
时间: 2024-06-14 20:05:15 浏览: 7
以下是用C语言结构体编写的孔融让梨程序:
```c
#include <stdio.h>
typedef struct {
int value; // 剩余资源数
struct process *L; // 等待队列
} semaphore;
typedef struct process {
int id; // 进程ID
struct process *next; // 下一个进程
} process;
void wait(semaphore *S, int id) {
S->value--;
if (S->value < 0) {
process *newProcess = (process *)malloc(sizeof(process));
newProcess->id = id;
newProcess->next = NULL;
if (S->L == NULL) {
S->L = newProcess;
} else {
process *current = S->L;
while (current->next != NULL) {
current = current->next;
}
current->next = newProcess;
}
}
}
void signal(semaphore *S) {
S->value++;
if (S->value <= 0) {
process *releasedProcess = S->L;
S->L = S->L->next;
free(releasedProcess);
}
}
int main() {
semaphore S;
S.value = 1;
S.L = NULL;
// 创建5个进程
process *p1 = (process *)malloc(sizeof(process));
p1->id = 1;
p1->next = NULL;
process *p2 = (process *)malloc(sizeof(process));
p2->id = 2;
p2->next = NULL;
process *p3 = (process *)malloc(sizeof(process));
p3->id = 3;
p3->next = NULL;
process *p4 = (process *)malloc(sizeof(process));
p4->id = 4;
p4->next = NULL;
process *p5 = (process *)malloc(sizeof(process));
p5->id = 5;
p5->next = NULL;
// 进程申请资源
wait(&S, p1->id);
wait(&S, p2->id);
wait(&S, p3->id);
wait(&S, p4->id);
wait(&S, p5->id);
// 输出等待队列中的进程ID
process *current = S.L;
while (current != NULL) {
printf("Process ID: %d\n", current->id);
current = current->next;
}
// 释放资源
signal(&S);
signal(&S);
signal(&S);
signal(&S);
signal(&S);
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)