Reputation: 5316
What is the most efficient way to keep checking if a certain something happened & if that something happened you execute a set of commands? (I'm working with C & Obj-C)
Upvotes: 1
Views: 849
Reputation: 5316
I found out that it is best is I create a thread that runs in the background until a condition is met
Upvotes: 1
Reputation: 4746
Use this.
NSTimer *newTimer = [NSTimer timerWithTimeInterval:5 target:self selector:@selector(checkBoolValue) userInfo:nil repeats:YES];
This method will run checkBoolValue after every 5 seconds.
Now, when your boolean value gets set, then stop the timer by
[newTimer invalidate];
newTimer = nil;
Upvotes: 4
Reputation: 39174
You can use busy waiting (bad idea because you waste cpu cycles):
while (true){
if(CheckConditionTrue()){
doSomething();
}
}
Better is use select function with a timeout, for example if you are waiting for file descriptor events. With select function you can listen for events happened on given file descriptors. The execution is blocked until an event happen or when the timeout limit is reached.
If you don't or can't use select, use I timeout (still better than busy waiting):
while (true){
nextTimeInterval();
//do what you want
}
void nextTimeInterval(){
sleep (INTERVAL_TO_SLEEP);
return;
}
Upvotes: 1
Reputation: 279285
Depends what kind of "certain something". Usually the most efficient is to have the thing that does the "certain something" notify you, using for example a semaphore, a condition variable, or an asynchronous I/O library. Then you just sleep waiting for the notification. What function you need to call to wait depends what kind of notification it is.
Upvotes: 1