停止,然后启动线程
Stop, and start thread?
有停止和启动线程的方法吗?我希望用户能够随意停止和启动一个功能。例如:
void func()
{
while (1)
{
cout << "I am a function!" << endl;
}
}
void stopfunc();
{
if (condition...)
t1.stop(); (???)
}
}
int main()
{
thread t1(func);
thread t2(stopfunc)
t1.join();
t2.join();
}
编辑:我尝试了评论中的建议,但没有奏效:
atomic<bool> stop_func{ false };
void toggle()
{
while (1)
{
Sleep(20);
if (GetAsyncKeyState(VK_F6))
{
stop_func = true;
}
}
}
int Func()
{
while (!stop_func)
{
HWND h = FindWindow(NULL, "....");
if (!process->Attach("..."))
return 1;
Interface::OnSetup();
Static::OnSetup();
Dynamic::OnSetup();
if (!g_pOverlay->Attach(h))
return 2;
g_pRenderer->OnSetup(g_pOverlay->GetDevice());
hFont = g_pRenderer->CreateFont("Verdana", 12, FONT_CREATE_SPRITE | FONT_CREATE_OUTLINE | FONT_CREATE_BOLD);
g_pOverlay->AddOnFrame(OnFrame);
return g_pOverlay->OnFrame();
}
}
int main()
{
thread t1(Func);
thread t2(toggle);
t1.join();
t2.join();
}
我做错了什么?
没有直接的、可移植的方法来启动或停止线程。
您可以通过设置一个标志,并在设置了标志时/如果设置了标志,就让线程屈服:
class foo {
std::atomic<bool> flag;
public:
void pause() { flag = true; }
void unpause() { flag = false; }
void operator() {
for (;;) {
if (flag) yield();
_do_other_stuff();
}
}
};
如果您确实需要线程完全停止,可以使用native_handle
来获得线程的本机句柄。然后,由于您显然是为Windows编写的,所以您可以使用SuspendThread
和ResumeThread
来真正挂起和恢复线程——当然,编写这样做的代码是不可移植的。
相关文章:
- 使用 std::string () const 函数启动线程或未来
- 如何创建线程序列以按照启动顺序执行任务?
- 启动类函数作为失去引用的线程
- 重新启动后,线程无法在 while 循环中再次运行
- 如何在C++上启动异步线程
- 计时器是否从另一个线程启动?
- 如何在 MFC 应用程序中启动 ZeroMQ 线程?
- C++ POCO - 如何在不使用 run() 方法的情况下启动线程池上的线程?
- 为什么 pthread_create() 返回 0 但线程从未启动
- 为什么 cuda-gdb 会启动多个线程?
- 对于每个线程,random_device是否以不同的状态启动?
- 线程启动延迟 - 通知所有未唤醒所有线程
- 等待多个线程启动,start() 未捕获
- Qt多线程启动线程错误
- 用信号通知线程启动特定的函数
- C++简单的线程启动问题
- - C++ - 使用计时器线程启动异常,精度毫秒
- 传递字符串作为线程启动例程参数:c++
- 错误:无法从另一个线程启动计时器.使用未声明计时器的QFuture
- QT线程:获取QObject::startTimer:计时器无法从另一个线程启动警告