static std::atomic_bool lmb_down(false);
static std::atomic_bool rmb_down(false);
void do_work()
{
for (int i = 0; i < 10; i++)
{
if (lmb_down.load() && rmb_down.load())
{
// DO SOMETHING
std::this_thread::sleep_for(std::chrono::seconds(1));
}
else break;
}
return;
}
int main()
{
MouseState state;
while (get_mouse_button_event(&state))
{
switch (state)
{
case 1:
lmb_down = true;
break;
case 2:
lmb_down = false;
break;
case 3:
rmb_down = true;
break;
case 4:
rmb_down = false;
}
if (lmb_down.load() && rmb_down.load())
{
std::thread t1(do_work);
std::detach();
}
}
return 0;
}
What I want?
If both mouse buttons are pressed down then I want to start some work in another thread. If one or both mouse buttons were released then I want to stop all active worker threads.
What is the problem?
If mouse button was released and again pressed while worker thread was sleeping then do_work loop continues to do its work, but it should exit. (also another thread will be created, but that is desired)
How I tried to solve the problem?
I tried to use futures instead of global variables, but managing all the futures for new threads was too messy.