【问题标题】:How to avoid a mutex variable being locked twice by the same thread?如何避免互斥变量被同一个线程锁定两次?
【发布时间】:2015-07-26 08:04:00
【问题描述】:

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;
}

现在,考虑来自此链接的以下信息:https://computing.llnl.gov/tutorials/pthreads/#ConVarSignal

pthread_cond_wait() - 这个例程应该在互斥锁被锁定时调用,它会在等待时自动释放互斥锁。

接收到信号并唤醒线程后,互斥量将自动锁定以供线程使用。

然后程序员负责在线程完成后解锁互斥锁。

当从另一个线程接收到信号时,pthread_cond_wait 将锁定互斥锁以供该线程使用,这意味着在我的情况下,控件将进入 if 语句,其中互斥锁已被 pthread_cond_wait 锁定(从其他条件),我们现在再次锁定它。

是不是我写错了代码逻辑?怎么样?

【问题讨论】:

  • qt 标签在这里是相关的,因为QList 的使用可能是线程安全的,也可能不是线程安全的..

标签: c++ multithreading qt pthreads


【解决方案1】:

在检查条件之前,您应该始终保持锁定。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2011-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多