我无法关闭我的线程。我忘记做某事了吗?该线程似乎正在保存我用于关闭的值,然后从不检查它是否已更改。下面是一些具有相同效果的示例代码:
#include "stdafx.h"
#include "Windows.h"
#include <iostream>
#include <thread>
class test {
private:
bool user_wants_thread = true;
bool time_to_close = false;
public:
bool set_timetoclose(bool in) {
time_to_close = in;
if (time_to_close == in) {
return true;
}
return false;
}
void function() {
while (user_wants_thread) {
// CODE
std::cout << time_to_close;
Sleep(100);
if (time_to_close) {
goto close;
}
}
close:
Sleep(1);
}
};
int main() {
test t;
std::thread thread_func(&test::function, t);
Sleep(1000);
bool success;
do {
success = t.set_timetoclose(true);
} while (!success);
thread_func.join();
std::cout << "Closed";
std::cin.get();
}
最佳答案
我删除了一些未使用的部分并将实际情况更改为 atomic<bool>
它似乎如此链接所示工作:
http://rextester.com/TWHK12491
不过,我并不是说这是绝对正确的,但它显示了使用 atomic 如何导致跨读取/写入值的同步,这可能导致数据竞争。
#include "Windows.h"
#include <iostream>
#include <thread>
#include <atomic>
class test {
public:
std::atomic<bool> time_to_close = false;
test()=default;
void function() {
while (!time_to_close) {
std::cout << "Running..." << std::endl;
Sleep(100);
}
std::cout << "closing" << std::endl;
}
};
int main() {
test t;
std::thread thread_func([&t](){t.function();});
Sleep(500);
t.time_to_close = true;
std::cout << "Joining on thread" << std::endl;
thread_func.join();
std::cout << "Closed";
return 0;
}
关于c++ - 线程终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46085379/