c语言通过多线程实现信箱的操作流程,实现信箱大小为3,发送接收10次的代码
时间: 2024-06-18 15:03:12 浏览: 15
通过多线程实现信箱的操作流程可以使用线程同步的方法,利用信号量或互斥锁等机制来保证线程间的互斥访问和同步操作。下面是实现信箱大小为3,发送接收10次的c语言代码:
```
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#define MAX_SIZE 3 // 定义信箱的最大大小
#define MAX_MSG 10 // 定义发送接收消息的次数
int mailbox[MAX_SIZE]; // 定义一个数组模拟信箱
int in = 0, out = 0; // 定义两个指针,in指向下一个可写位置,out指向下一个可读位置
sem_t empty, full; // 定义两个信号量,empty表示空闲空间的数量,full表示已占用空间的数量
void *producer(void *arg) {
int i, item;
for (i = 0; i < MAX_MSG; i++) {
item = i;
sem_wait(&empty); // 等待空闲空间
mailbox[in] = item; // 将消息写入信箱
in = (in + 1) % MAX_SIZE; // 指针移动到下一个可写位置
printf("Producer: %d\n", item);
sem_post(&full); // 释放已占用空间
}
return NULL;
}
void *consumer(void *arg) {
int i, item;
for (i = 0; i < MAX_MSG; i++) {
sem_wait(&full); // 等待已占用空间
item = mailbox[out]; // 从信箱中读取消息
out = (out + 1) % MAX_SIZE; // 指针移动到下一个可读位置
printf("Consumer: %d\n", item);
sem_post(&empty); // 释放空闲空间
}
return NULL;
}
int main() {
pthread_t tid1, tid2;
sem_init(&empty, 0, MAX_SIZE); // 初始化empty为MAX_SIZE
sem_init(&full, 0, 0); // 初始化full为0
pthread_create(&tid1, NULL, producer, NULL);
pthread_create(&tid2, NULL, consumer, NULL);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
sem_destroy(&empty);
sem_destroy(&full);
return 0;
}
```
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)