如何在另一个线程中终止一个线程 [英] How to terminate a thread in another thread
本文介绍了如何在另一个线程中终止一个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在C ++中使用std :: thread创建了线程。
I have created thread by using std::thread in C++.
std::thread thread_variable(function_name);
使用上面的代码,它将创建一个线程。
我需要在另一个中使用thread_variable来终止这个线程线程,比如TerminateThread()win32 api。
如何做到这一点?
谢谢
我尝试了什么:
我试过使用std :: thread的析构函数,但是线程是运作良好。
谢谢
With above code, it will create a thread.
And I need to terminate this thread by using thread_variable in another thread, like TerminateThread() win32 api.
How can this be done?
Thank you
What I have tried:
I have tried to use desctructor of std::thread, but thread is working well.
Thank you
推荐答案
不要再次发布同样的问题。标准的C ++
无法做你想做的事。 Rick York 发布了此处 [ ^ ]完成任务的常用方法。
另一种方法是通过线程使用操作系统的基础API
native_handle
。
例如,请参阅 c ++ - 如何在不终止程序的情况下停止运行std :: thread - Stack Overflow [ ^ ]。
Don't post again and again the same question. There is no way in standardC++
to do what you want. Rick York posted here[^] the usual way to accomplish the task.
An alternative is using the underlyingAPI
of your operative system by means of the threadnative_handle
.
See, for instance c++ - How to stop an std::thread from running, without terminating the program - Stack Overflow[^].
可能有不同的解决方案,最明显的是使用全局变量(布尔,互斥或句柄)表示退出。
伪代码:
There are different solutions possible, the most obvious is to use a global variable (boolean, mutex or handle) to signal the exit.
pseudo-code:
bool stopThread = false;
void threadOne()
{
if( timeToLeave ) {
stopThread = true;
}
}
void threadTwo()
{
while( !stopThread ) {
//do silly stuff, maybe some waiting
}
}
如果您不喜欢它,请阅读 documenation 和也许你可以做类似的事情
If you dont like it read the documenation and "maybe" you can do stuff like that
std::thread *myThread = new std::thread(...);//some working constructor
delete myThread;
祝你好运...
这篇关于如何在另一个线程中终止一个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文