Linux管道(Pipe)确实可以用于线程间通信,但需要注意一些关键点。
虽然管道可用,但在线程通信中通常更推荐使用以下机制:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
void *reader(void *arg) {
int fd = *(int *)arg;
char buf[256];
ssize_t n;
while ((n = read(fd, buf, sizeof(buf))) > 0) {
printf("Received: %.*s", (int)n, buf);
}
return NULL;
}
void *writer(void *arg) {
int fd = *(int *)arg;
const char *msg = "Hello from writer thread\n";
write(fd, msg, strlen(msg));
close(fd); // 关闭写入端
return NULL;
}
int main() {
int pipefd[2];
pthread_t t1, t2;
pipe(pipefd);
pthread_create(&t1, NULL, reader, &pipefd[0]);
pthread_create(&t2, NULL, writer, &pipefd[1]);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
return 0;
}
虽然Linux管道可以用于线程通信,但在大多数情况下,专门的线程同步机制会更高效、更适合。选择通信机制时应考虑: - 通信模式(单向/双向) - 性能要求 - 代码复杂度 - 可维护性
在需要类似进程间通信模型的线程通信场景中,管道是一个可行的选择。