gpt4 book ai didi

c++ - 在使用pthread_create 创建的线程之间读写管道时是否需要关闭fds?

转载 作者:太空宇宙 更新时间:2023-11-04 07:10:48 24 4
gpt4 key购买 nike

我正在处理一个客户端服务器应用程序。以下是来自客户端的代码。

pipe_input, pipe_output 是共享变量。

        int fds[2];
if (pipe(fds)) {
printf("pipe creation failed");
} else {
pipe_input = fds[0];
pipe_output = fds[1];
reader_thread_created = true;
r = pthread_create(&reader_thread_id,0,reader_thread,this);
}


void* reader_thread(void *input)
{
unsigned char id;
int n;
while (1) {

n = read(pipe_input , &id, 1);
if (1 == n) {
//process
}if ((n < 0) ) {
printf("ERROR: read from pipe failed");
break;
}
}
printf("reader thread stop");
return 0;
}

还有一个写入线程,它写入来自服务器的事件更改数据。

void notify_client_on_event_change(char id)
{
int n;
n= write(pipe_output, &id, 1);
printf("message written to pipe done ");
}

我的问题是我是否需要关闭读取器线程中的写入端和写入器线程中的读取端。在析构函数中,我正在等待读取线程退出,但有时它不会从读取线程退出。

最佳答案

[...] do i need to close the write end in reader thread and read end in case of writer thread[?]

因为那些 fds“是共享的”,在一个线程中关闭它们会为所有线程关闭它们。我怀疑那不是你想要的。

关于c++ - 在使用pthread_create 创建的线程之间读写管道时是否需要关闭fds?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28559599/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com