pthread_cond_timedwait()

前端 未结 7 1554
有刺的猬
有刺的猬 2020-12-16 05:22
void wait(int timeInMs)
{
    struct timespec timeToWait;
    timeToWait.tv_sec = 5;
    timeToWait.tv_nsec = timeInMs*1000;

    int rt;

    pthread_mutex_lock(&am         


        
7条回答
  •  眼角桃花
    2020-12-16 06:15

    Main reference: http://pubs.opengroup.org/onlinepubs/009695299/functions/pthread_cond_timedwait.html

    FIX of the code of andrewrk above

    I can confirm Adrian May that gettimeofday doesn't function correctly! The code behavior of andrewrk inside an infinite thread like this

    static void * thread_infinite(void * unused) {
    while (1) {
            // compute stuff
            mywait(5);
    }
    

    is unpredictable: it runs approximate 700 times more until it blocks!

    The correct version of the code of andrewrk is:

    pthread_mutex_t fakeMutex = PTHREAD_MUTEX_INITIALIZER;
    pthread_cond_t fakeCond = PTHREAD_COND_INITIALIZER;
    
    void mywait(int timeInS)
    {
        struct timespec ts;
        struct timeval now;
        int rt = 0;
    
    //    gettimeofday(&now,NULL); // DOES NOT FUNCTION CORRECTLY
    //    timeToWait.tv_sec = now.tv_sec+5;
    //    timeToWait.tv_nsec = (now.tv_usec+1000UL*timeInMs)*1000UL;
    
        clock_gettime(CLOCK_REALTIME, &ts);
        ts.tv_sec += timeInS;
    
        pthread_mutex_lock(&fakeMutex);
    
        do {
            rt = pthread_cond_timedwait(&fakeCond, &fakeMutex, &ts);
            }
        while (rt == 0);
    
        pthread_mutex_unlock(&fakeMutex);
    }
    

提交回复
热议问题