线程终止
Terminating while thread
我无法关闭线程。我忘了做某事吗?该线程似乎正在保存我用于关闭的值,然后再也没有检查它是否已更改。这是一些具有相同效果的示例代码:
#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
我并不是说这是绝对正确的,但是它表明了如何使用原子原因跨读/写入可能导致数据竞赛的值同步。
#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++
- 自终止线程.使用联接或分离
- 从c/c 中终止线程中的线程,而无需线柄
- 无法终止线程(错误 6)
- 定时与终止线程使用事件不一致
- C++ WinSock Recv 在接收 0 数据时终止线程而不是返回错误代码
- 立即终止线程
- 如何在C++11中终止线程
- 在 C++11 中从外部终止线程
- 错误地终止线程
- 终止线程后的清理
- 如何在Windows线程中终止线程后获取剩余线程数?C++
- 终止线程
- 分段错误,使用 pthread_exit() 终止线程时
- 可以终止线程从另一个进程终止线程
- 正在终止线程
- 如何知道何时终止线程
- C++:如何在没有特定"interruption points"的情况下干净地终止线程
- 强制终止线程C++win32
- 想要终止线程池一旦变量达到一定的值