I have some variable which is written by one thread and read by another (or several) thread. I want the read threads to be able to wait for the variable to become a certain value without constantly polling it. How can I do this in a threadsafe way? My initial idea was: Read Thread:
- check the variable for the correct value inside a lock. if correct -> do something, if not -> continue.
- wait on AutoResetEvent signal, then check for the correct value inside a lock. if correct -> do something, if not -> redo this step
Write thread:
- write the new variable value inside a lock
- signal AutoResetEvent that the value has changed
If the read thread checks the value and it is not correct, the write thread may signal the AutoResetEvent before the read thread begins waiting. This means the read thread will keep waiting forever(or until the value changes again). Is there some pattern which solves this issue?