【发布时间】:2017-04-23 22:19:15
【问题描述】:
我有一个std::thread 可能在文件描述符输入/输出调用中被阻止,我怎样才能彻底取消它?
考虑以下示例:
#include <unistd.h>
#include <thread>
void thread_routine(int fd)
{
char buf;
read(fd, &buf, 1);
}
int main()
{
int pipefd[2];
pipe(pipefd);
std::thread thread(&thread_routine, pipefd[0]);
thread.join();
close(pipefd[0]);
close(pipefd[1]);
}
在join() 之前我可以做什么来确保它不会永远锁定? (管道只是获取文件描述符的一种快速示例方法,我有一个more exotic scenario,但我试图得到一个通用的答案。)
使用 pthreads 我可以调用 pthread_cancel(),因为 read() 和 write() 是取消点,但是没有 C++ 方法可以取消 std::thread(我可以获取 thread::native_handle() 并将其传递给 pthread_cancel(),但我想要一种更清洁的方法)。
请注意:
- 我无法在非阻塞模式下设置文件描述符
- 我不能在文件描述符上使用 select()
【问题讨论】:
标签: c++ multithreading c++11 posix file-descriptor