LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Regarding Sleep() function in c (https://www.linuxquestions.org/questions/programming-9/regarding-sleep-function-in-c-870914/)

jyothidamu 03-25-2011 05:51 AM

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

Aquarius_Girl 03-25-2011 06:00 AM

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

Nominal Animal 03-25-2011 07:35 AM

Quote:

Originally Posted by jyothidamu (Post 4302785)
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.

posixculprit 03-25-2011 08:06 AM

Quote:

Originally Posted by Anisha Kaul (Post 4302791)
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?

Aquarius_Girl 03-25-2011 09:33 AM

Quote:

Originally Posted by posixculprit (Post 4302900)
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.

posixculprit 03-25-2011 09:53 AM

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.

Aquarius_Girl 03-25-2011 09:59 AM

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?

posixculprit 03-25-2011 10:23 AM

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.

Aquarius_Girl 03-25-2011 10:26 AM

Thanks again, keep on correcting me :)

nime 03-26-2011 03:13 PM

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?

Nominal Animal 03-26-2011 04:33 PM

Quote:

Originally Posted by nime (Post 4304509)
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.)

Sergei Steshenko 03-26-2011 04:46 PM

Quote:

Originally Posted by Nominal Animal (Post 4304568)
...
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.

nime 03-26-2011 04:59 PM

Hello Nominal!:D, 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?

Sergei Steshenko 03-26-2011 05:03 PM

Quote:

Originally Posted by nime (Post 4304587)
Hello Nominal!:D, 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.

nime 03-26-2011 05:15 PM

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 :)


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