需要帮助调试互斥锁死锁

时间:2012-03-07 15:48:43

标签: c++ linux pthreads mutex deadlock

我在以下代码中有一个互斥锁死锁:

CRegistry::CRegistry()
{
    pthread_mutex_init(&_Mutex, NULL);
}

CRegistry::~CRegistry()
{
    pthread_mutex_destroy(&_Mutex);
}

MR_RESULT CRegistry::Register(const REGISTRY_KEY &Id, const REGISTRY_ITEM &Item)
{
    pair<REGISTRY::iterator, bool> Result;

    pthread_mutex_lock(&_Mutex);
    Result = _Registry.insert(pair<REGISTRY_KEY, REGISTRY_ITEM>(Id, Item));
    pthread_mutex_unlock(&_Mutex);

    if (Result.second == true)
        return MR_RESULT_OK;
    else
        return MR_RESULT_ERROR;
}

MR_RESULT CRegistry::UnRegister(const REGISTRY_KEY &Id)
{
    REGISTRY::size_type Result;

    pthread_mutex_lock(&_Mutex);
    Result = _Registry.erase(Id);
    pthread_mutex_unlock(&_Mutex);

    if (Result == 1)
        return MR_RESULT_OK;
    else
        return MR_RESULT_ERROR;
}

_Mutext是类成员,不会在代码中的任何其他位置使用。在某些时候,我可以看到线程卡住试图锁定已经锁定的互斥锁。

有实时和非实时线程锁定互斥锁。我知道可以有优先级倒置,但这怎么会造成死锁?

2 个答案:

答案 0 :(得分:2)

您的代码对我来说似乎完全没问题。你确定在其他任何地方都没有使用_Mutex吗?

Valgrind工具集包括Helgrind,这是一个pthread调试器,可以帮助您解决死锁问题。也许你可以运行它。

答案 1 :(得分:0)

您确定其他优先级较高的线程会长时间阻塞死锁或线程吗?

您是否考虑过使用

pthread_mutexattr_setprotocol (&attr, PTHREAD_PRIO_INHERIT)

避免优先级倒置问题?

相关问题