停止,然后启动线程?

时间:2015-04-06 23:12:35

标签: c++ multithreading

有没有办法停止并启动一个线程?我希望用户能够随意停止并启动一个功能。 例如:

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();
}

我做错了什么?

1 个答案:

答案 0 :(得分:0)

没有直接的,可移植的方式来启动或停止线程。

你可以通过设置一个标志来相当接近,并且当/如果设置了标志时让线程产生:

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来真正暂停和恢复该线程 - 但当然,代码执行该操作的代码不会便携式。