user7070
user7070

Reputation: 21

Make the current thread sleep for particular time in C

I want to know if there is anyway to make the current thread to sleep for a particular interval of time in C. I have lots of files in the project and want only one function in the file to sleep for particular time while can access other functions in the same file. Something like below i want to do -

void otherfunction() <-- other programs should be able to access otherfunction() when somefunction() is sleeping.

   void somefunction()
   {
       //sleep for 2sec.
   }

Upvotes: 2

Views: 2131

Answers (2)

sth
sth

Reputation: 229844

The POSIX function for sleeping is called sleep(). You call it with the number of seconds as a parameter.

Upvotes: 2

Leonardo Bernardini
Leonardo Bernardini

Reputation: 1116

This is a microseconds sleep function , for cross-platform sleeping:

void MicroSleep(int n) {
    #ifdef WIN32
        ::Sleep(n);
    #else
        struct timeval tm;
        unsigned long seconds = n/1000;
        unsigned long useconds = n%1000;
        if (useconds > 1000) { useconds -= 1000; seconds++; }
        useconds*=1000; // using usec
        tm.tv_sec = seconds;
        tm.tv_usec = useconds;
        select(0, 0, 0, 0, &tm);
    #endif
}

Upvotes: 0

Related Questions