C - 如何在同一进程中使用管道(线程安全)



我正在尝试在同一进程中使用管道:

define MAX_SIZE 200
int read_port;
int send_port;
void init()
{
int fd[2];
pipe(fd);
read_port = fd[0];
send_port = fd[1];
}
void consume(void* destination) {
//read from pipe and store the content to destination
read(read_port, destination, MAX_SIZE);
}
void channel_send(void* message) {
write(send_port,message,MAX_SIZE)
}

将有许多线程写入管道,但只有 1 个线程要从管道读取。此代码中是否存在一些潜在问题?该程序有时会由于某种原因而被阻止,但我不知道出了什么问题。

使用 POSIX 信号量使写入操作成为关键部分的示例代码

#include <semaphore.h> 
#include <unistd.h> 
sem_t mutex; 
void channel_send(void* message) {
sem_wait(&mutex);
write(send_port,message,MAX_SIZE);
sem_post(&mutex); 
}

这使得write()命令具有原子性。

最新更新