1

我想知道是否可以使用互斥锁自己制作递归互斥锁类型,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?!但两者的行为方式相同......?

这个解决方案安全吗?

4

1 回答 1

2

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

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

于 2014-04-13T12:56:26.637 回答