Advertisement

sleep, usleep and giving up a threads time...

Started by May 03, 2003 01:21 AM
2 comments, last by avianRR 20 years, 11 months ago
I''m woking on a program that I need to have delays of milliseconds. I tried usleep but it always returns immediatly with no delay. Sleep on the other hand works fine but I only have 1000ms resolution on the delays. problem two, if there''s nothing for a thread to do I want to give up the thread''s time so another thread can run then come back to my loop later. In win32 I can do this with "sleep(0);" but in linux it just return''s immedatly. Any help appreciated. Thanks, Rob
------------------------------Piggies, I need more piggies![pig][pig][pig][pig][pig][pig]------------------------------Do not invoke the wrath of the Irken elite. [flaming]
sleep(0) will have the same thread yielding effect under linux. However, if all other threads are waiting/sleeping, it will immediately re-run.

How appropriate. You fight like a cow.
Advertisement
The program I''m working on has a semiphore where I can only let one of the threads access a data set at one time. After the main control thread checks the data and exits the semiphored section of code I call sleep(0) to let the other threads have access to the data if they need it then I loop back through the semiphored code again. I''m printing the PID of the thread that want''s to use it then the PID of the thread that enters that section of code and I''ll see the main thread get the semiphore like 10 times after another thread say''s it wan''t it. If the sleep(0) were giving up the main threads time then it should allow the other treads acces to the code before it run''s though again let alone 10 more times.

example output...

Main: checking data.
Main: checking data.
PID 6870 want''s data rights.
Main: checking data.
Main: checking data.
PID 7140 want''s data rights.
Main: checking data.
Main: checking data.
Main: checking data.
Main: checking data.
Main: checking data.
Main: checking data.
Main: checking data.
Main: checking data.
Main: checking data.
PID 7140 got data rights.
Main: checking data.
Main: checking data.
Main: checking data.

etc...
the main look looks like this.

void CheckData(){
while(continueChecking){
GetDataRights();
ProcessData();
ReleaseDataRights();
sleep(0);
}
}

If I change it to sleep(1) it let''s the other threads have the data rights after right away. But that creat''s more of a delay than I want. usleep returns immediatly regardless of what value I give it.
kind of a late response to an old thread (no pun intended) but maybe somebody will get use out of this

i believe sched_yield() will forfeit the remainder of a threads time

This topic is closed to new replies.

Advertisement