停止,然后启动线程

Stop, and start thread?

本文关键字:线程 启动 然后 停止      更新时间:2023-10-16

有停止和启动线程的方法吗?我希望用户能够随意停止和启动一个功能。例如:

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编写的,所以您可以使用SuspendThreadResumeThread来真正挂起和恢复线程——当然,编写这样做的代码是不可移植的。