我有以下通过线程执行的示例代码(请参见下面的代码):
A: rd-lock
B: wr-lock (waiting)
A: rd-lock (recursive)
A: rd-unlock (recursive)
A: rd-unlock
B: wr-locked (wake after wait)
B: wr-unlock.
基本上读锁是递归的。它是 POSIX 标准所要求的(要求读锁是递归的,但没有为写锁指定)。这适用于 Linux、FreeBSD、Solaris,但不适用于 Darwin/Mac OS X。
下面的示例在 Linux 上提供以下输出:
read locking
read locked
write locking
read locking 2
read locked 2
read unlocked 2
read unlocked
write locked
write unlocked 2
在达尔文上打印:
read locking
read locked
write locking
read locking 2
而这里的死锁(不继续),基本上是不尊重递归读锁的。
有什么可以做的(标记、定义、链接到一个特殊的库版本)可以按预期工作吗?
示例代码
#include <pthread.h>
#include <stdio.h>
pthread_rwlock_t lock;
void *thread_r(void *p)
{
printf("read locking\n");
pthread_rwlock_rdlock(&lock);
printf("read locked\n");
usleep(500*1000);
printf("read locking 2\n");
pthread_rwlock_rdlock(&lock);
printf("read locked 2\n");
usleep(500*1000);
pthread_rwlock_unlock(&lock);
printf("read unlocked 2\n");
usleep(500*1000);
pthread_rwlock_unlock(&lock);
printf("read unlocked\n");
}
void *thread_w(void *p)
{
usleep(250*1000);
printf("write locking\n");
pthread_rwlock_wrlock(&lock);
printf("write locked\n");
pthread_rwlock_unlock(&lock);
printf("write unlocked 2\n");
}
int main()
{
pthread_t a,b;
pthread_rwlock_init(&lock,NULL);
pthread_create(&a,NULL,thread_r,0);
pthread_create(&b,NULL,thread_w,0);
pthread_join(a,NULL);
pthread_join(b,NULL);
return 0;
}