简体   繁体   English

如何避免互斥变量被同一线程两次锁定?

[英]How to avoid a mutex variable being locked twice by the same thread?

queueLIFO is QList queueLIFOQList

//  This function is run by the thread `Producer`.
void *threadProducerFunction (void *arg)
{
    Q_UNUSED (arg);

    while (1)
    {
        if (queueLIFO.length () < 10)
        {
            pthread_mutex_lock (&mutexVariable);
            queueLIFO.push_back (1);
            pthread_mutex_unlock (&mutexVariable);
        }
        else
        {
            pthread_mutex_lock (&mutexVariable);
            pthread_cond_wait (&conditionVariable, &mutexVariable);
        }
    }
    return NULL;
}

Now, considering the following info from this link: https://computing.llnl.gov/tutorials/pthreads/#ConVarSignal 现在,考虑来自此链接的以下信息: https : //computing.llnl.gov/tutorials/pthreads/#ConVarSignal

pthread_cond_wait() - this routine should be called while mutex is locked, and it will automatically release the mutex while it waits. pthread_cond_wait() -互斥锁被锁定时应调用此例程,并且它将在等待时自动释放互斥锁。

After signal is received and thread is awakened, mutex will be automatically locked for use by the thread. 接收到信号并唤醒线程后,互斥锁将自动锁定以供线程使用。

The programmer is then responsible for unlocking mutex when the thread is finished with it. 线程完成后,程序员负责解锁互斥锁。

When the signal is received from the other thread, pthread_cond_wait will lock the mutex for this thread's usage, which means that in my situation the control will go in the if statement where the mutex is already locked by pthread_cond_wait (from else condition) and we are locking it again now. 当从另一个线程收到信号时, pthread_cond_wait将锁定该线程的互斥锁以供该线程使用,这意味着在我的情况下,该控件将进入if语句,其中该互斥锁已被pthread_cond_wait锁定(来自else条件),我们现在再次锁定它。

Have I written the code logic in a wrong way? 我是否以错误的方式编写了代码逻辑? How? 怎么样?

You should always hold the lock before you check the condition. 检查状况之前,应始终握住锁。

pthread_mutex_lock (&mutexVariable);
while (queueLIFO.length() >= 10) {
    pthread_cond_wait (&conditionVariable, &mutexVariable);
}
queueLIFO.push_back (1);
pthread_mutex_unlock (&mutexVariable);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM