Reputation: 65
Is there a way to stop and start a thread? I want the user to be able to stop and start a function at will. ex:
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();
}
EDIT: I tried what someone in the comments suggested, this didn't work:
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();
}
What am I doing wrong?
Upvotes: 1
Views: 3068
Reputation: 490138
There isn't a direct, portable way to start or stop a thread.
You can come fairly close by setting a flag, and having the thread yield when/if the flag is set:
class foo {
std::atomic<bool> flag;
public:
void pause() { flag = true; }
void unpause() { flag = false; }
void operator() {
for (;;) {
if (flag) yield();
_do_other_stuff();
}
}
};
If you really need the thread to stop completely, you can use native_handle
to get a native handle to the thread. Then, since you're apparently writing for Windows, you can use you can use SuspendThread
and ResumeThread
to truly suspend and resume the thread--but of course, code the code that does that won't be portable.
Upvotes: 1