Daniel
Daniel

Reputation: 389

Pattern for thread to check if it should stop?

Is there a canonical pattern for a thread to check if it should stop working?

The scenario is that a thread is spinning a tight working loop but it should stop if another thread tells it to. I was thinking of checking an atomic bool in the loop condition but I'm not sure if that is an unnecessary performance hit or not. E.g.

std::atomic<bool> stop{false};
while(!stop){
  //...
}

Upvotes: 4

Views: 1137

Answers (2)

Hans Olsson
Hans Olsson

Reputation: 12507

You have to make it atomic (or volatile in old C/C++) to ensure that the compiler doesn't optimize it away and only test stop once.

If you call a function in the loop that cannot be inlined (like reading sockets) you might be safe with a non-atomic bool, but why risk it - especially as the atomic read is unlikely to be a performance issue in that case?

To have the least effect you could do something like:

std::atomic<bool> stop;
void rx_thread() {
  // ...
  while(!stop.load(std::memory_order_relaxed)){
    ..
  }
}

Upvotes: 2

Georg P.
Georg P.

Reputation: 3164

I don't see any reason why the bool should be atomic. There isn't really a potential for a race condition. When you want to stop the thread, you first set the variable to true and then issue a call that wakes up the blocking function inside the loop (however you do that, depends on the blocking call).

bool stop = false;

void rx_thread() {
  // ...
  while(!stop){
    // ...
    blocking_call();
    // ...
  }
}

void stop_thread() {
  stop = true;
  wakeup_rx_thread();
}

If the blocking call happens to wake up between setting stop to true and calling wakeup_rx_thread(), then the loop will finish anyway. The call to wakeup_rx_thread() will be needless, but that doesn't matter.

Upvotes: -1

Related Questions