【发布时间】:2019-04-22 15:49:44
【问题描述】:
我有一个使用 asio 库连接到套接字的应用程序。我的主线程调用open() 到套接字实现,然后它与主线程分离以继续执行。
当thread::detach() 被调用时,线程不能再被加入,因此调用者不知道线程何时完成执行。至少在我的应用程序中,这会导致不干净的关闭。资源未正确释放,并且仅在某些情况下会导致崩溃。是否可以重新加入分离的线程?我想尽量避免使用条件变量。
这是我的例子:
io_socket io = new io_socket();
// The call to thread::detach() is done within io_socket::open()
io->open();
// Let some things happen...
std::this_thread::sleep_for(std::chrono::seconds(20));
// Safely kills all operations and resources before delete
io->close();
// A hack solution to allow time for the detached thread to do what it needs to do
//std::this_thread::sleep_for(std::chrono::milliseconds(1000));
// Crashes if I don't allow the detached thread to safely close
delete io;
return EXIT_SUCCESS;
【问题讨论】:
-
使用某种条件变量并让
close等待,直到所有分离的线程通知它们完成。 -
@NathanOliver 我应该把它放在我原来的帖子中,但如果可能的话,我会尽量避免使用条件变量。我希望有一个更干净的解决方案,比如加入一个分离的线程。虽然我知道目前的规范是不可能的。
-
要么提供自己的同步机制,要么不使用
detach。 -
我能问一下为什么线程首先被分离了吗?为什么没有
io_socket的std::thread m_thread成员并让io_socket析构函数执行必要的清理?
标签: c++ multithreading c++-standard-library stdthread