当前位置: 技术问答>linux和unix
Linux的pthread的读写锁是否可以写优先?
来源: 互联网 发布时间:2015-06-01
本文导语: 发现一个现象: (1)thread1中pthread_rwlock_rdlock(&a)成功后; (2)thread2中pthread_rwlock_wrlock(&a)不成功; (3)thread3中再次pthread_rwlock_rdlock(&a)又成功。 我希望第三步中的pthread_rwlock_rdlock(&a)不成功,怎么办? 望高手指教,...
发现一个现象:
(1)thread1中pthread_rwlock_rdlock(&a)成功后;
(2)thread2中pthread_rwlock_wrlock(&a)不成功;
(3)thread3中再次pthread_rwlock_rdlock(&a)又成功。
我希望第三步中的pthread_rwlock_rdlock(&a)不成功,怎么办?
望高手指教,谢谢!
(1)thread1中pthread_rwlock_rdlock(&a)成功后;
(2)thread2中pthread_rwlock_wrlock(&a)不成功;
(3)thread3中再次pthread_rwlock_rdlock(&a)又成功。
我希望第三步中的pthread_rwlock_rdlock(&a)不成功,怎么办?
望高手指教,谢谢!
|
默认就是写优先的,再检查一下你的代码。
#define _XOPEN_SOURCE 500
#include
# define PTHREAD_RWLOCK_INITIALIZER_READ_PREF { {0, 0}, 0, NULL, NULL, NULL, PTHREAD_RWLOCK_PREFER_READER_NP, PTHREAD_PROCESS_PRIVATE }
static pthread_rwlock_t a = PTHREAD_RWLOCK_INITIALIZER;
void *route_3 (void *p)
{
sleep(2);
printf("locking 3 = %dn", pthread_rwlock_rdlock(&a));
pause();
return NULL;
}
void *route_2 (void *p)
{
sleep(1);
printf("locking 2 = %dn", pthread_rwlock_wrlock(&a));
pause();
return NULL;
}
void *route_1 (void *p)
{
printf("locking 1 = %dn", pthread_rwlock_rdlock(&a));
pause();
return NULL;
}
main()
{
pthread_t t1, t2, t3;
pthread_create(&t1, NULL, route_1, NULL);
pthread_create(&t2, NULL, route_2, NULL);
pthread_create(&t3, NULL, route_3, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
pthread_join(t3, NULL);
}
这个例子如果把a初始化成PTHREAD_RWLOCK_INITIALIZER_READ_PREF ,才是读优先的,你可以试一下,如果不对,就只有怀疑线程库看源码了。
#define _XOPEN_SOURCE 500
#include
# define PTHREAD_RWLOCK_INITIALIZER_READ_PREF { {0, 0}, 0, NULL, NULL, NULL, PTHREAD_RWLOCK_PREFER_READER_NP, PTHREAD_PROCESS_PRIVATE }
static pthread_rwlock_t a = PTHREAD_RWLOCK_INITIALIZER;
void *route_3 (void *p)
{
sleep(2);
printf("locking 3 = %dn", pthread_rwlock_rdlock(&a));
pause();
return NULL;
}
void *route_2 (void *p)
{
sleep(1);
printf("locking 2 = %dn", pthread_rwlock_wrlock(&a));
pause();
return NULL;
}
void *route_1 (void *p)
{
printf("locking 1 = %dn", pthread_rwlock_rdlock(&a));
pause();
return NULL;
}
main()
{
pthread_t t1, t2, t3;
pthread_create(&t1, NULL, route_1, NULL);
pthread_create(&t2, NULL, route_2, NULL);
pthread_create(&t3, NULL, route_3, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
pthread_join(t3, NULL);
}
这个例子如果把a初始化成PTHREAD_RWLOCK_INITIALIZER_READ_PREF ,才是读优先的,你可以试一下,如果不对,就只有怀疑线程库看源码了。