Archived

This topic is now archived and is closed to further replies.

avianRR

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

Recommended Posts

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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
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.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
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

Share this post


Link to post
Share on other sites