我有2个线程监视同一全局state
,如果state.shutdown
变成false
,则线程run()
应该返回。代码如下。
#include <iostream>
#include <chrono>
#include <thread>
#include <mutex>
using namespace std;
struct State {
bool shutdown = false;
~State() {
shutdown = true;
}
};
State state;
#define CHECK_SHUTDOWN \
{ \
std::cout << (state.shutdown ? " SHUTDOWN " : " NOSHUT ") << typeid(*this).name() << std::endl; \
if (state.shutdown) { \
return; \
} \
}
class Mythread {
public:
void join();
void run();
void launch();
std::thread self_thread;
};
void Mythread::run() {
while(1) {
CHECK_SHUTDOWN
}
}
void Mythread::join() {
if (self_thread.joinable()) {
self_thread.join();
}
}
void Mythread::launch() {
self_thread = std::thread(&Mythread::run,this);
}
std::mutex mtx;
void shut() {
std::lock_guard<std::mutex> lock(mtx);
state.shutdown = true;
}
int main()
{
Mythread thread1;
Mythread thread2;
thread1.launch();
thread2.launch();
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
//state.shutdown = true;
shut(); //This makes no difference with the line above
std::this_thread::sleep_for(std::chrono::milliseconds(100));
thread1.join();
thread2.join();
return 0;
}
但是,即使我手动将state.shutdown
设置为true,线程也永远无法检测到它。我有类似的照片:
NOSHUT 8Mythread
NOSHUT 8Mythread
NOSHUT 8Mythread
...Program finished with exit code 0
Press ENTER to exit console.
最后。鉴于永不返回run()
函数,线程连接应该挂起,我也感到困惑。但是,线程可以成功加入。
任何帮助在这里都将不胜感激!