Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pthread_cond_timedwait()

Tags:

c

pthreads

void wait(int timeInMs)
{
    struct timespec timeToWait;
    timeToWait.tv_sec = 5;
    timeToWait.tv_nsec = timeInMs*1000;

    int rt;

    pthread_mutex_lock(&fakeMutex);
    rt = pthread_cond_timedwait(&fakeCond, &fakeMutex, &timeToWait);
    pthread_mutex_unlock(&fakeMutex);
}

I'm using this code to try to get a thread to wait around for a bit, but it doesn't work at all. No errors, it just doesn't make the program execute any slower.

I was thinking maybe each thread needs to have it's own condition and mutex, but that really doesn't make sense to me.

like image 312
Ciph3rzer0 Avatar asked Sep 28 '09 12:09

Ciph3rzer0


People also ask

What is pthread_cond_timedwait?

The pthread_cond_timedwait() function atomically unlocks the mutex and performs the wait for the condition. In this case, atomically means with respect to the mutex and the condition variable and other access by threads to those objects through the pthread condition variable interfaces.

Does Pthread_cond_wait block?

The pthread_cond_wait() function blocks the calling thread, waiting for the condition specified by cond to be signaled or broadcast to. When pthread_cond_wait() is called, the calling thread must have mutex locked.

What is Pthread_cond_initializer?

Description. The PTHREAD_COND_INITIALIZER macro initializes the static condition variable cond, setting its attributes to default values. This macro should only be used for static condition variables, since no error checking is performed.

What does pthread cond broadcast do?

The pthread_cond_signal() function wakes up at least one thread that is currently waiting on the condition variable specified by cond. If no threads are currently blocked on the condition variable, this call has no effect.


1 Answers

The pthread_cond_timedwait function takes an absolute time, not a relative time. It takes the time you want to stop waiting, not how long you want to wait.

like image 60
David Schwartz Avatar answered Jan 04 '23 13:01

David Schwartz