Problem with pThread sync issue

前端 未结 5 1098
温柔的废话
温柔的废话 2020-12-29 00:27

I am facing a sync issue with pthread. threadWaitFunction1, is a thread wait function. I expect line no. 247 flag = 1 to be executed only after 243-246 has fini

5条回答
  •  醉话见心
    2020-12-29 01:20

    As stated by Alexey Kukanov, the problem is likely spurious wakeup. your code may be corrected to loop until timeout occurs. Note that I also moved the flag setting to be under the mutex.

    static void* threadWaitFunction1(void *timeToWaitPtr)
    {
        struct timespec *ptr = (struct timespec*) timeToWaitPtr;
        int ret;
    
        pthread_mutex_lock(&timerMutex);
        cout << "Setting flag =0 inside threadWaitFunction1\n";
        flag=0;
        cout << "Inside threadWaitFunction\n";
        while (pthread_cond_timedwait(&timerCond, &timerMutex, ptr) != ETIMEDOUT)
            ;
        cout << "Setting flag =1 inside threadWaitFunction1\n";
        flag=1;
        pthread_mutex_unlock(&timerMutex);
    }
    

    To be on the safe side, you should check the flag under the same mutex to establish ordering

提交回复
热议问题