C++ 终止工作线程的正确方法
嗨,我正在尝试找到终止工作线程的最佳方法。我有以下代码:C++ 终止工作线程的正确方法,c++,multithreading,C++,Multithreading,嗨,我正在尝试找到终止工作线程的最佳方法。我有以下代码: class test{ public: test() {} ~test() {} std::atomic<bool> worker_done; int a; void pr() { while (true) { if (worker_done) { break; } std::this_thread::sleep_for(std::chr
class test{
public:
test() {}
~test() {}
std::atomic<bool> worker_done;
int a;
void pr() {
while (true) {
if (worker_done) {
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(500));
printf("%d \n", a++);
}
}
std::thread* m_acqThread;
void continuous() {
m_acqThread = new std::thread(&test::pr, this);
}
void stopThread(){
if (m_acqThread) {
if (m_acqThread->joinable())
m_acqThread->join();
delete m_acqThread;
m_acqThread = nullptr;
}
}
};
int main(){
test t;
t.continuous();
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
t.worker_done = true;
t.stopThread();
std::string str;
std::cin.clear();
getline(std::cin, str);
return 0;
类测试{
公众:
test(){}
~test(){}
std::原子工人完成;
INTA;
无效pr(){
while(true){
如果(已完成){
打破
}
std::this_线程::sleep_for(std::chrono::毫秒(500));
printf(“%d\n”,a++);
}
}
std::thread*m_acqThread;
void continuous(){
m_acqThread=newstd::thread(&test::pr,this);
}
void stopThread(){
if(m_acqThread){
if(m_acqThread->joinable())
m_acqThread->join();
删除m_acqThread;
m_acqThread=nullptr;
}
}
};
int main(){
试验t;
t、 连续();
std::this_线程::sleep_for(std::chrono::毫秒(2000));
t、 worker_done=真;
t、 止动螺纹();
std::字符串str;
std::cin.clear();
getline(标准::cin,str);
返回0;
除了将“worker_done”设置为true之外,还有没有更好的方法通知工作线程终止
谢谢你所拥有的一切都很好:如果你有一个
线程
,它说当你的程序打开时启动,当你的程序关闭时你需要停止它,那么使用原子
是正确的方法
也可以这样使用:
“…最好的和平方式…”有暴力的方法吗?请使用
unique\u ptr
而不是手动指针跟踪。非恶意杀戮是我认为他/她所指的术语std::thread
没有用于此的接口。使用野蛮方法或标志。否。工作线程需要知道你希望它结束。因此必须发送一个信号。原子标志会吗更好吗?至少atomic
是便宜的。atomic标志听起来像一个被遗忘的50年代超级英雄。atomic_标志
没有测试操作,只有test_and_set
和clear
。用这些原语发送另一个线程是不必要的困难。唯一的优点是,它由标准定义为应该是无锁的,而不是实现定义的。但是atomic
在所有主要实现上都是无锁的。(没有注意到TA已经讨论了atomic\u标志
)
#include <thread>
#include <atomic>
#include <iostream>
std::atomic_flag lock;
int n = 0;
void t()
{
while (lock.test_and_set())
{
++n;
std::this_thread::sleep_for(std::chrono::milliseconds(250));
}
}
int main()
{
lock.test_and_set();
std::thread t(&t);
std::this_thread::sleep_for(std::chrono::seconds(2));
lock.clear();
t.join();
std::cout << n << std::endl;
std::cin.get();
}
std::atomic<bool> runThread;
int n = 0;
void t()
{
while (runThread)
{
++n;
std::this_thread::sleep_for(std::chrono::milliseconds(250));
}
}
int main()
{
runThread = true;
std::thread t(&t);
std::this_thread::sleep_for(std::chrono::seconds(2));
runThread = false;
t.join();
std::cout << n << std::endl;
std::cin.get();
}