Search This Blog

Wednesday, September 30, 2009

Sleep-ing in pthread

Using any variant of sleep for pthreads, the behaviour is not guaranteed. All the threads can also sleep since the kernel is not aware of the different threads. Hence a solution is required which the pthread library can handle rather than the kernel.

A safer and cleaner solution to use is the pthread_cond_timedwait...

pthread_mutex_t fakeMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t fakeCond = PTHREAD_COND_INITIALIZER;

void mywait(int timeInSec)
struct timespec timeToWait;
struct timeval now;
int rt;


timeToWait.tv_sec = now.tv_sec + timeInSec;
timeToWait.tv_nsec = now.tv_usec*1000;

rt = pthread_cond_timedwait(&fakeCond, &fakeMutex, &timeToWait);

void* fun(void* arg)
printf("\nIn thread\n");

int main()
pthread_t thread;
void *ret;

pthread_create(&thread, NULL, fun, NULL);

For pthread_cond_timedwait , you need to specify how much time to wait from current time.

Now by the use of the function mywait() only the thread calling it will sleep and not the other pthreads.

Note : I have not checked the return values of the functions for error. Please do the same.


Jitesh Shah said...

does pthread_cond_wait have any issues?

Furquan Shaikh said...

pthread_cond_wait waits indefinitely for the condition on which it is waiting to become true...

whereas pthread_cond_timedwait only waits for a specific amount of time.

As far as i tested it, there seems to be no issues with pthread_cond_timedwait

Post a Comment