C++ 可终止线程类
我正在尝试设计一个killable_thread类,它派生自std::thread。这是继我就这个问题所作的发言之后的又一次发言 以下是killable_线程类(v2)的源代码: 也就是说,虽然我处理异常并在die()成员中设置异常,但测试人员会中止,因为我没有将()与线程联接 当我使用线程join()时,运行时错误会消失(自然): 事实上,这正是我想要的killable\u thread所做的,而不需要在测试仪中加入C++ 可终止线程类,c++,multithreading,C++,Multithreading,我正在尝试设计一个killable_thread类,它派生自std::thread。这是继我就这个问题所作的发言之后的又一次发言 以下是killable_线程类(v2)的源代码: 也就是说,虽然我处理异常并在die()成员中设置异常,但测试人员会中止,因为我没有将()与线程联接 当我使用线程join()时,运行时错误会消失(自然): 事实上,这正是我想要的killable\u thread所做的,而不需要在测试仪中加入 我如何才能让它工作?您意识到die()正在主线程中抛出异常,并且在线程运行f
我如何才能让它工作?您意识到
die()
正在主线程中抛出异常,并且在线程运行f()
时不执行任何操作,对吗?我认为你走错了方向。你实际上想用killable_thread
解决什么问题?正如@DarkFalcon所说:“我怎样才能让它工作?”:你不能。在没有来自操作系统的未定义行为的情况下杀死线程的唯一方法是:在线程中(重复)测试一个原子请退出变量,然后通过抛出异常或优雅地退出返回顶层来干净地退出。这是您需要离开您的解决方案空间,并更多地思考您试图解决的原始问题。还有一个更好的方法。@DarkFalcon,我正在尝试设计一个方法来告诉正在运行的线程停止运行并释放其资源。“我正在尝试设计一个方法来告诉正在运行的线程停止运行并释放其资源。”为什么?你这么做想解决什么问题?
#include <thread> /// thread
#include <exception> /// exception_ptr
#include <iostream> /// cout, endl
template<typename Tsk,
typename... Args>
class killable_thread : public std::thread
{
private:
std::exception_ptr& pex;
public:
/// inherit the thread class' constructor
/// [CPL], $20.3.5.1
using std::thread::thread;
using std::thread::operator=;
killable_thread(std::exception_ptr& pe,
Tsk tsk,
Args... args) :
thread {tsk, args...},
pex {pe}
{
}
void die()
{
try
{
std::cout << "diag: dying..." << std::endl;
throw std::runtime_error
{"thread instructed to die."};
}
catch (std::exception& e)
{
/** Set the exception_ptr to point to
this exception, so that it may be
propagated out of this thread. **/
pex = std::current_exception();
}
}
};
/// Tester ...
/// declarations ...
void test1();
void f();
std::exception_ptr pex {};
int main()
{
test1();
}
void test1()
{
try
{
killable_thread<decltype(f)> kt {pex, f};
kt.die();
if (pex)
std::rethrow_exception(pex);
std::cout << "thread didn't die."
<< std::endl;
}
catch (std::exception& e)
{
std::cout << "exception: " << e.what()
<< std::endl;
}
}
void f()
{
}
diag: dying...
terminate called without an active exception
bash: line 7: 22929 Aborted (core dumped) ./a.out
void test1()
{
try
{
killable_thread<decltype(f)> kt {pex, f};
kt.die();
kt.join();
if (pex)
std::rethrow_exception(pex);
std::cout << "thread didn't die."
<< std::endl;
}
catch (std::exception& e)
{
std::cout << "exception: " << e.what()
<< std::endl;
}
}
diag: dying...
exception: thread instructed to die.