错误检查互斥锁与递归互斥锁

时间:2014-04-13 12:39:12

标签: c multithreading pthreads mutex recursive-mutex

我想知道我是否可以使用PTHREAD_MUTEX_ERRORCHECK互斥锁自行创建递归互斥锁类型,结果如下:

typedef struct {
    pthread_mutex_t mutex;
    uint32_t deadlocks;
    pthread_t owner;
    BOOL isLocked;
} pthread_recursivemutex_t;

int pthread_recursivemutex_init(pthread_recursivemutex_t *mutex)
{
    int ret;
    pthread_mutexattr_t attr;

    mutex->deadlocks = 0;

    ret = pthread_mutexattr_init(&attr);

    if (ret != 0) {
        return ret;
    }

    (void)pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK);

    ret = pthread_mutex_init(&mutex->mutex, &attr);

    (void)pthread_mutexattr_destroy(&attr);

    mutex->isLocked = FALSE;

    return ret;
}

void pthread_recursivemutex_lock(pthread_recursivemutex_t *mutex)
{
    int ret;
    BOOL locked;

    locked = mutex->isLocked;
    __sync_synchronize();

    if (locked == TRUE) {
        if (pthread_equal(pthread_self(), mutex->owner) == 0) {
            return;
        }
    }       

    ret = pthread_mutex_lock(&mutex->mutex);

    if (ret == 0) {
        mutex->deadlocks = 0;
        __sync_synchronize();
        mutex->isLocked = TRUE;
    } else if (ret == EDEADLK) {
        mutex->deadlocks += 1;
    }
}

void pthread_recursivemutex_unlock(pthread_recursivemutex_t *mutex)
{
    if (mutex->deadlocks == 0) {
        (void)pthread_mutex_unlock(&mutex->mutex);
        __sync_synchronize();
        mutex->isLocked = FALSE;
    } else {
        mutex->deadlocks -= 1;
    }
}

void pthread_recursivemutex_destroy(pthread_recursivemutex_t *mutex)
{
    (void)pthread_mutex_destroy(&mutex->mutex);
}

我发现这种类型的递归互斥锁比具有PTHREAD_MUTEX_RECURSIVE属性的互斥锁快得多:

iterations               : 1000000

pthread_mutex_t          : 71757 μSeconds
pthread_recursivemutex_t : 48583 μSeconds

测试代码(每次调用1000000次):

void mutex_test()
{
    pthread_mutex_lock(&recursiveMutex);
    pthread_mutex_lock(&recursiveMutex);
    pthread_mutex_unlock(&recursiveMutex);
    pthread_mutex_unlock(&recursiveMutex);
}

void recursivemutex_test()
{
    pthread_recursivemutex_lock(&myMutex);
    pthread_recursivemutex_lock(&myMutex);
    pthread_recursivemutex_unlock(&myMutex);
    pthread_recursivemutex_unlock(&myMutex);
}

pthread_recursivemutex_t几乎是pthread_mutex_t的两倍?但两者的行为方式相同......?

这个解决方案是否安全?

1 个答案:

答案 0 :(得分:1)

您的互斥锁不起作用:您不检查哪个线程正在获取锁定。

您允许多个线程锁定相同的互斥锁。