LinuxQuestions.org
Download your favorite Linux distribution at LQ ISO.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
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

Reply
 
Search this Thread
Old 03-25-2011, 05:51 AM   #1
jyothidamu
LQ Newbie
 
Registered: Mar 2011
Posts: 7

Rep: Reputation: 0
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.
Old 03-25-2011, 06:00 AM   #2
TheIndependentAquarius
Senior Member
 
Registered: Dec 2008
Posts: 4,622
Blog Entries: 29

Rep: Reputation: 896Reputation: 896Reputation: 896Reputation: 896Reputation: 896Reputation: 896Reputation: 896
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 TheIndependentAquarius; 03-25-2011 at 10:28 AM. Reason: correction pointed by posixculprit
 
Old 03-25-2011, 07:35 AM   #3
Nominal Animal
Senior Member
 
Registered: Dec 2010
Location: Finland
Distribution: Xubuntu, CentOS, LFS
Posts: 1,723
Blog Entries: 3

Rep: Reputation: 942Reputation: 942Reputation: 942Reputation: 942Reputation: 942Reputation: 942Reputation: 942Reputation: 942
Quote:
Originally Posted by jyothidamu View Post
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.
 
Old 03-25-2011, 08:06 AM   #4
posixculprit
Member
 
Registered: May 2010
Posts: 136

Rep: Reputation: 42
Quote:
Originally Posted by Anisha Kaul View Post
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?
 
Old 03-25-2011, 09:33 AM   #5
TheIndependentAquarius
Senior Member
 
Registered: Dec 2008
Posts: 4,622
Blog Entries: 29

Rep: Reputation: 896Reputation: 896Reputation: 896Reputation: 896Reputation: 896Reputation: 896Reputation: 896
Quote:
Originally Posted by posixculprit View Post
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.
 
Old 03-25-2011, 09:53 AM   #6
posixculprit
Member
 
Registered: May 2010
Posts: 136

Rep: Reputation: 42
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.
Old 03-25-2011, 09:59 AM   #7
TheIndependentAquarius
Senior Member
 
Registered: Dec 2008
Posts: 4,622
Blog Entries: 29

Rep: Reputation: 896Reputation: 896Reputation: 896Reputation: 896Reputation: 896Reputation: 896Reputation: 896
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?
 
Old 03-25-2011, 10:23 AM   #8
posixculprit
Member
 
Registered: May 2010
Posts: 136

Rep: Reputation: 42
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.
Old 03-25-2011, 10:26 AM   #9
TheIndependentAquarius
Senior Member
 
Registered: Dec 2008
Posts: 4,622
Blog Entries: 29

Rep: Reputation: 896Reputation: 896Reputation: 896Reputation: 896Reputation: 896Reputation: 896Reputation: 896
Thanks again, keep on correcting me
 
1 members found this post helpful.
Old 03-26-2011, 03:13 PM   #10
nime
LQ Newbie
 
Registered: Jan 2011
Location: Croatia
Distribution: Ubuntu 9.1
Posts: 28

Rep: Reputation: 1
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?
 
Old 03-26-2011, 04:33 PM   #11
Nominal Animal
Senior Member
 
Registered: Dec 2010
Location: Finland
Distribution: Xubuntu, CentOS, LFS
Posts: 1,723
Blog Entries: 3

Rep: Reputation: 942Reputation: 942Reputation: 942Reputation: 942Reputation: 942Reputation: 942Reputation: 942Reputation: 942
Quote:
Originally Posted by nime View Post
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.)
 
Old 03-26-2011, 04:46 PM   #12
Sergei Steshenko
Senior Member
 
Registered: May 2005
Posts: 4,481

Rep: Reputation: 453Reputation: 453Reputation: 453Reputation: 453Reputation: 453
Quote:
Originally Posted by Nominal Animal View Post
...
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.
 
Old 03-26-2011, 04:59 PM   #13
nime
LQ Newbie
 
Registered: Jan 2011
Location: Croatia
Distribution: Ubuntu 9.1
Posts: 28

Rep: Reputation: 1
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?
 
Old 03-26-2011, 05:03 PM   #14
Sergei Steshenko
Senior Member
 
Registered: May 2005
Posts: 4,481

Rep: Reputation: 453Reputation: 453Reputation: 453Reputation: 453Reputation: 453
Quote:
Originally Posted by nime View Post
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.
 
Old 03-26-2011, 05:15 PM   #15
nime
LQ Newbie
 
Registered: Jan 2011
Location: Croatia
Distribution: Ubuntu 9.1
Posts: 28

Rep: Reputation: 1
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.
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
use of sleep function in fedora shivi91 Programming 2 03-03-2011 09:17 PM
Use of Sleep function in Perl Russell Griffiths Programming 2 08-14-2006 04:37 AM
How to disable the Monitor Sleep function under RH9 ?? 242VDM242 Linux - Newbie 1 05-21-2005 01:51 PM
looking for a Sleep() function Mike Davies Linux - Software 2 10-25-2004 08:11 AM
Is the wait function is the same as the sleep function ? Linh Programming 3 04-28-2004 12:39 PM


All times are GMT -5. The time now is 07:11 PM.

Main Menu
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration