Not locking mutex for pthread_cond_timedwait and pthread_cond_signal ( on Linux )

前端 未结 6 1643
小蘑菇
小蘑菇 2020-12-10 08:17

Is there any downside to calling pthread_cond_timedwait without taking a lock on the associated mutex first, and also not taking a mutex lock when calling pthread_cond_signa

6条回答
  •  心在旅途
    2020-12-10 08:47

    I think this should work (note untested code):

    // initialize a semaphore
    sem_t sem;
    sem_init(&sem,
        0, // not shared
        0  // initial value of 0
        );
    
    
    // thread A
    struct timespec tm;
    struct timeb    tp;
    
    const long sec      = msecs / 1000;
    const long millisec = msecs % 1000;
    
    ftime(&tp);
    tp.time += sec;
    tp.millitm += millisec;
    if(tp.millitm > 999) {
        tp.millitm -= 1000;
        tp.time++;
    }
    tm.tv_sec  = tp.time;
    tm.tv_nsec = tp.millitm * 1000000;
    
    // wait until timeout or woken up
    errno = 0;
    while((sem_timedwait(&sem, &tm)) == -1 && errno == EINTR) {
        continue;
    }
    
    return errno == ETIMEDOUT; // returns true if a timeout occured
    
    
    // thread B
    sem_post(&sem); // wake up Thread A early
    

提交回复
热议问题