dimanche 25 octobre 2020

Propagating modifications to reference variables to thread after it has been detached

I have encountered the following situation:

I'm constructing a std::thread, passing a functions that takes a parameter abort of type std::atomic<bool> &. The idea here is that I will set this parameter to true in the main thread when I want the thread to abort execution (e.g. by breaking out of loop). What I have notices is that this always works I join the thread afterwards but only sometimes works when I detach it (which is what I would rather do because I don't require the value returned by the thread after I have set abort to true). Why is this? Can I still achieve what I want? I.e. somehow signal the thread to stop execution and then detach it?

Here's a pseudo-example:

std::atomic<bool> abort(false);

std::packaged_task<void()> task(
  [&]() {
    for (;;) {
      if (abort.load())
        break;

      // do work
    }
  });

auto future(task.get_future());

std::thread thread(std::move(task));

if (future.wait_for(std::chrono::milliseconds(100)) == std::future_status::timeout) {
  abort.store(true);

  thread.detach() // abort.load() does not deterministically return true!

  // timeout, do something

} else {
  thread.join();

  // no timeout, do something
}

Aucun commentaire:

Enregistrer un commentaire