编写一个C程序,使用管道机制实现线程间的通信
时间: 2024-10-21 09:13:08 浏览: 33
Java中利用管道实现线程间的通讯
在C语言中,实现线程间的通信通常不是通过管道(pipe),因为管道主要用于进程间通信(IPC)。然而,如果你想演示一种不同类型的进程间通信,如共享内存或消息队列,这里以共享内存为例:
**共享内存示例[^1]**:
```c
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#define BUFFER_SIZE 10
void producer(int fd, char *buffer) {
for (int i = 0; i < BUFFER_SIZE; ++i) {
buffer[i] = i;
printf("Producer wrote %d\n", i);
sleep(1); // 暂停以允许消费者查看
}
close(fd);
}
void consumer(int fd, char *buffer) {
while (true) {
if (read(fd, buffer, BUFFER_SIZE) == -1) break; // 结束标志
printf("Consumer read %d\n", buffer[0]);
}
close(fd);
}
int main() {
int shm_fd = shm_open("/my_shared_memory", O_RDWR | O_CREAT, 0644);
char *buffer = mmap(NULL, BUFFER_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
if (shm_fd == -1 || buffer == MAP_FAILED) {
perror("Error opening/sharing memory");
return 1;
}
// 创建生产者线程
pthread_t producer_thread;
if (pthread_create(&producer_thread, NULL, producer, &shm_fd) != 0) {
perror("Error creating producer thread");
return 1;
}
// 创建消费者线程
pthread_t consumer_thread;
if (pthread_create(&consumer_thread, NULL, consumer, &shm_fd) != 0) {
perror("Error creating consumer thread");
return 1;
}
// 等待线程结束
pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);
munmap(buffer, BUFFER_SIZE);
shm_close(shm_fd);
return 0;
}
```
这个例子展示了如何创建一个共享内存区域并在两个线程间传递数据。`producer`线程写入数据,而`consumer`线程读取数据。
阅读全文