Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for a boolean without looping (using any kind of wait / semaphore / event / mutex, etc)

Tags:

I need to stop a thread until another thread sets a boolean value and I don't want to share between them an event.

What I currently have is the following code using a Sleep (and that's the code I want to change):

while (!_engine.IsReadyToStop()) {     System.Threading.Thread.Sleep(Properties.Settings.Default.IntervalForCheckingEngine);  } 

Any ideas?

EDIT TO CLARIFY THINGS:

There is an object called _engine of a class that I don't own. I cannot modify it, that's why I don't want to share an event between them. I need to wait until a method of that class returns true.

like image 553
Ignacio Soler Garcia Avatar asked Sep 13 '12 18:09

Ignacio Soler Garcia


1 Answers

SpinWait.SpinUntil is the right answer, regardless where you're gonna place this code. SpinUntil offers "a nice mix of spinning, yielding, and sleeping in between invocations".

like image 116
MoonStom Avatar answered Sep 19 '22 22:09

MoonStom