public void Test1() { var mutex = new object(); var cv = new ConditionVariable <int>(); bool ready = false; bool processed = false; // Main { var worker = new Thread(new ThreadStart(WorkerThread)).Run(); // send data to the worker thread lock (mutex) { ready = true; cv.NotifyOne(mutex, 1); } // wait for the worker lock (mutex) { var value = cv.Wait(mutex, x => processed); Assert.Equal(value, 42); } worker.Join(); } void WorkerThread() { // Wait until main() sends data lock (mutex) { var value = cv.Wait(mutex, x => ready); Assert.Equal(value, 1); // after the wait, we own the lock. cv.NotifyOne(mutex, 42); // Send data back to main() processed = true; } } }
public async void Test2() { var cv = new ConditionVariable(); var data = (string?)null; var ready = false; var processed = false; // Main { var worker = new Thread(new ThreadStart(WorkerThread)).Run(); data = "Example data"; // send data to the worker thread ready = true; cv.NotifyOne(); // wait for the worker await cv.WaitAsync(() => processed); // "Back in main(), data = " << data << '\n'; Assert.Equal(data, "Changed data"); worker.Join(); } async void WorkerThread() { // Wait until main() sends data await cv.WaitAsync(() => ready); // after the wait, we own the lock. data = "Changed data"; // Send data back to main() processed = true; // Should be notifying outside of the lock but C# Monitor.Pulse is // not quite the same as std::condition_variable.notifiy_all() cv.NotifyOne(); } }