Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game. |
Notices |
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
Are you new to LinuxQuestions.org? Visit the following links:
Site Howto |
Site FAQ |
Sitemap |
Register Now
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
|
 |
|
03-25-2011, 05:51 AM
|
#1
|
LQ Newbie
Registered: Mar 2011
Posts: 7
Rep:
|
Regarding Sleep() function in c
Hi there
I know what is the functionality of the sleep() method.
for(i = 0; i < length; i++){
sleep(1000);
printf("%c\n", message[i]);
}
Result :every print of the message will be takes 1000sec of gap
but i want to know why wee need to use the Sleep function. where exactly it is useful
Thanking you
reddy
|
|
|
Click here to see the post LQ members have rated as the most helpful post in this thread.
|
03-25-2011, 06:00 AM
|
#2
|
Senior Member
Registered: Dec 2008
Posts: 4,732
|
One use: (In a layman's language) sleep() can be used to synchronize make threads wait, i.e. when you want one thread to pause till another one completes its task.
You might like to read about the terms:
sleep
wait
pthread
Last edited by Aquarius_Girl; 03-25-2011 at 10:28 AM.
Reason: correction pointed by posixculprit
|
|
|
03-25-2011, 07:35 AM
|
#3
|
Senior Member
Registered: Dec 2010
Location: Finland
Distribution: Xubuntu, CentOS, LFS
Posts: 1,723
|
Quote:
Originally Posted by jyothidamu
i want to know why wee need to use the Sleep function. where exactly it is useful
|
One excellent example is when you need to periodically measure or check something. For example:
Code:
#define _BSD_SOURCE
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
double v[1];
int r;
while ((r = getloadavg(&v, 1)) >= 1) {
printf("%.6f\n", v[0]);
sleep(5);
}
return 0;
}
The above program will print out the CPU load (averaged over the last minute) every five seconds.
If you replaced the sleep(5) with a loop that waits until the system timer has progressed five seconds, the program would work the same way from the user's perspective -- but it would waste massive amounts of CPU processing time for nothing. It would be extremely wasteful. (That kind of loop would be called spinning or busy-waiting, and should always be avoided.)
The sleep(5), on the other hand, tells the kernel that this process (or thread) does not have any work to do for the next five seconds (unless something interesting happens, like a signal is delivered), so the CPU can be given to other processes. If the load is low enough, the kernel can decide to put the CPU to a lower power state, saving quite a bit of energy.
Hope this helps.
|
|
|
03-25-2011, 08:06 AM
|
#4
|
Member
Registered: May 2010
Posts: 136
Rep:
|
Quote:
Originally Posted by Anisha Kaul
sleep() can be used to synchronize threads
|
I'm very curious to know just how one can (reliably) synchronize threads using sleep(). Care to point to some resources regarding this technique or providing the explanation yourself?
|
|
|
03-25-2011, 09:33 AM
|
#5
|
Senior Member
Registered: Dec 2008
Posts: 4,732
|
Quote:
Originally Posted by posixculprit
I'm very curious to know just how one can (reliably) synchronize threads using sleep(). Care to point to some resources regarding this technique or providing the explanation yourself?
|
https://computing.llnl.gov/tutorials/pthreads/
pthread_join can be used instead of sleep by the way.
and secondly I never claimed that sleep is the most reliable way. If you think tutorial is wrong in using it, then do bother to enlighten me please.
|
|
|
03-25-2011, 09:53 AM
|
#6
|
Member
Registered: May 2010
Posts: 136
Rep:
|
The resource you cited does not use sleep() as a method of synchronizing threads. It appears to be used in an attempt to prevent any particular thread from repeatedly acquiring a lock on the mutex thus starving the other threads. And, by the way, pthread_join can't be used instead of sleep() (not in general nor in the code contained in the article you provided as back-up for your claims).
To recap: the tutorial is not wrong in using it because it is not using it in the way you claim it is using it.
|
|
2 members found this post helpful.
|
03-25-2011, 09:59 AM
|
#7
|
Senior Member
Registered: Dec 2008
Posts: 4,732
|
Aaah, yes yes, now I realize the use of word "synchronize" was wrong. Thanks, that's how we learn. and pthread_join can be used as a wait. Is that term correct now?
|
|
|
03-25-2011, 10:23 AM
|
#8
|
Member
Registered: May 2010
Posts: 136
Rep:
|
I suppose one could claim some degree of similarity between pthread_join and waitpid given that they do somewhat similar things with regards to threads and processes, respectively.
|
|
2 members found this post helpful.
|
03-25-2011, 10:26 AM
|
#9
|
Senior Member
Registered: Dec 2008
Posts: 4,732
|
Thanks again, keep on correcting me 
|
|
1 members found this post helpful.
|
03-26-2011, 03:13 PM
|
#10
|
LQ Newbie
Registered: Jan 2011
Location: Croatia
Distribution: Ubuntu 9.1
Posts: 28
Rep:
|
Hello,
when we're by sleep function I should ask...
Why sleep function don't work for me in windows xp with codeblocks and gcc?
Functions from pthreads works well but I can't get sleep.
Compiler says:
Quote:
||=== gtktext, Debug ===|
C:\RTM\gtktext\main.c||In function 'main':|
C:\RTM\gtktext\main.c|199|warning: implicit declaration of function 'sleep'|
obj\Debug\main.o||In function `main':|
C:\RTM\gtktext\main.c|199|undefined reference to `sleep'|
||=== Build finished: 1 errors, 1 warnings ===|
|
I have properly declared stdio.h and stdlib.h headers.
What else can be?
And, did sleep stops execution for number of seconds or milliseconds?
Is there a simple way to chose between them?
|
|
|
03-26-2011, 04:33 PM
|
#11
|
Senior Member
Registered: Dec 2010
Location: Finland
Distribution: Xubuntu, CentOS, LFS
Posts: 1,723
|
Quote:
Originally Posted by nime
Why sleep function don't work for me in windows xp with codeblocks and gcc?
|
sleep() is declared in unistd.h in POSIX systems.
I personally don't use Windows at all, but I understand that if you include windows.h and winbase.h, you can use Sleep(), which takes the number of milliseconds to sleep as a DWORD parameter.
For portability, nanosleep() (declared in time.h) is a much better choice. Here is a portable nap() function, which takes the number of seconds to sleep as a double (fractional seconds are ok). It will normally return zero (0.0), but if it is interrupted, it will return the number of seconds left (to sleep).
Code:
#include <time.h>
/** nap() - Sleep for some number of seconds.
* Return 0.0 if successful.
* If interrupted by e.g. a signal, return the time left (not slept).
*/
double nap(double const seconds)
{
long const secs = (long)seconds;
double const frac = seconds - (double)secs;
struct timespec req, rem;
int result;
if (seconds <= 0.0)
return 0.0;
req.tv_sec = (time_t)secs;
req.tv_nsec = (long)(1000000000.0 * frac);
if (req.tv_nsec > 999999999L)
req.tv_nsec = 999999999L;
rem.tv_sec = (time_t)0;
rem.tv_nsec = (long)0L;
result = nanosleep(&req, &rem);
if (result == -1)
return (double)rem.tv_sec
+ (double)rem.tv_nsec / 1000000000.0;
return 0.0;
}
nanosleep() also does not interfere with signals, so it has no side effects when used with threads.
( sleep() may be implemented internally with alarm()/ SIGALRM signal, which makes sleep() in portable threaded programs problematic.)
|
|
|
03-26-2011, 04:46 PM
|
#12
|
Senior Member
Registered: May 2005
Posts: 4,481
|
Quote:
Originally Posted by Nominal Animal
...
For portability, nanosleep() (declared in time.h) is a much better choice.
...
|
Not quite/always. From the manpage (man 2 nanosleep) :
Quote:
nanosleep() suspends the execution of the calling thread
|
.
And, indeed, as I recently discovered, if I want my whole process to sleep, and use 'nanosleep', 'nanosleep' keeps 100% CPU load. I think this "came" to me with SUSE-11.1, i.e. I think previously my single-thread process was sleeping quite nicely with 'nanosleep'.
To suspend a process one has to use 'sleep' or 'usleep' - the latter for fractional second if/when needed.
|
|
|
03-26-2011, 04:59 PM
|
#13
|
LQ Newbie
Registered: Jan 2011
Location: Croatia
Distribution: Ubuntu 9.1
Posts: 28
Rep:
|
Hello Nominal!  , my favourite C guru!
Unfortunately, my computer won't sleep with windows.h and winbase.h too.
Same error appears.
And with nap function I have this:
Quote:
C:\RTM\gtktext\cFuncs.c||In function 'nap':|
C:\RTM\gtktext\cFuncs.c|12|error: storage size of 'req' isn't known|
C:\RTM\gtktext\cFuncs.c|12|error: storage size of 'rem' isn't known|
C:\RTM\gtktext\cFuncs.c|26|warning: implicit declaration of function 'nanosleep'|
C:\RTM\gtktext\cFuncs.c|12|warning: unused variable 'rem'|
C:\RTM\gtktext\cFuncs.c|12|warning: unused variable 'req'|
||=== Build finished: 2 errors, 3 warnings ===|
|
I have time.h declared.
Is here possible to rewrite nap function to work with milliseconds?
|
|
|
03-26-2011, 05:03 PM
|
#14
|
Senior Member
Registered: May 2005
Posts: 4,481
|
Quote:
Originally Posted by nime
Hello Nominal!  , my favourite C guru!
Unfortunately, my computer won't sleep with windows.h and winbase.h too.
Same error appears.
And with nap function I have this:
I have time.h declared.
Is here possible to rewrite nap function to work with milliseconds?
|
You most likely don't have 'nanosleep' at all; Windows is not a POSIX-compliant system.
|
|
|
03-26-2011, 05:15 PM
|
#15
|
LQ Newbie
Registered: Jan 2011
Location: Croatia
Distribution: Ubuntu 9.1
Posts: 28
Rep:
|
Yes Sergei,
something is obviously missing here.
I am totally new in C and this kind of issues so I try reachable examples from net to learn C. Between others I try about 30 examples with pthreads and mutexes which are also from Posix and all of them works as expected.
Except ones which have sleep function.
This is how I know that sleep don't work for me.
But maybe here is some workaround suitable to apply to beginners.
Nominal already know which kind of help and which level of examples to give to me 
|
|
1 members found this post helpful.
|
All times are GMT -5. The time now is 03:08 PM.
|
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.
|
Latest Threads
LQ News
|
|