1

I have a thread that must wait until a condition is true or until a timer runs out and I was thinking which would be the best way to solve it, I though about condition variables but I am not sure if is the best method since I could have race condition, I would be happy to hear your suggestion.

Thank you.

  • 1
    You can easily do this with `condition_variable`, see the example on this page: https://en.cppreference.com/w/cpp/thread/condition_variable The condition and the condition variable should be protected by the same mutex. – VLL Nov 30 '22 at 09:23
  • 4
    Why would a condition variable introduce a race condition? I assume you're using a predicate that's based on a variable guarded by the same mutex as the lock passed to `std::condition_variable::wait_for` and there simply is no race condition. For a single thread waiting for a single wakeup you could also use `std::promise`/`std::future`... – fabian Nov 30 '22 at 09:24
  • The question title is pretty much a statement of a standard Use Case for `std::condition_variable::wait_for`. There's a lack of clarity about why that might invoke a race condition. Normal correct use of a condition variable does not. – Persixty Nov 30 '22 at 11:19

1 Answers1

-3

A simple way is to have a locked mutex that your thread can wait for. Your timer can then unlock the mutex when you want the thread to continue.

Lasersköld
  • 2,028
  • 14
  • 20
  • 3
    https://stackoverflow.com/questions/12551341/when-is-a-condition-variable-needed-isnt-a-mutex-enough – VLL Nov 30 '22 at 09:28