- 论坛徽章:
- 0
|
本帖最后由 o_unix 于 2013-02-21 15:59 编辑
大家好,我想测试读写锁,写线程一直不能获得锁,而是读线程一直占据着,代码如下:
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <pthread.h>
- #define size 10
- int i = 0;
- pthread_rwlock_t rwlock;
- void *read_func( void *arg);
- void *write_func( void *arg);
- int main( void)
- {
- int j = 2*size;
- pthread_t *tids = (pthread_t *)malloc( j*sizeof( pthread_t));
- pthread_rwlockattr_t rwlockattr;
- pthread_rwlockattr_init( &rwlockattr);
- pthread_rwlockattr_setkind_np (&rwlockattr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
- pthread_rwlock_init( &rwlock, NULL);
- int m = 0;
- for( m =0; m < j; m++)
- {
- if( m < size)
- {
- pthread_create( tids+m, NULL, write_func, (void*)m);
- }
- else
- {
- pthread_create( tids+m, NULL, read_func, (void *)m);
- }
- }
- for( m = 0; m < j; m++)
- {
- pthread_join( *(tids+m), (void *)0);
- }
- pthread_rwlock_destroy( &rwlock);
- return 0;
- }
- void * read_func( void *arg)
- {
- while( i < 10)
- {
- pthread_rwlock_rdlock( &rwlock);
- printf("%d reading i:%d\n", (int)arg, i);
- pthread_rwlock_unlock( &rwlock);
- }
- void *write_func( void *arg)
- {
- pthread_rwlock_wrlock( &rwlock);
- printf("%d read i: %d\n", (int)arg, i++);
- printf("%d writing i: %d\n", (int)arg, i);
- pthread_rwlock_unlock( &rwlock);
- }
-
复制代码 我查看锁的状态的发现:
(gdb) print rwlock
$13 = {__data = {__lock = 0, __nr_readers = 10,
__readers_wakeup = 0, __writer_wakeup = 0,
__nr_readers_queued = 0, __nr_writers_queued = 10,
__writer = 0, __pad1 = 0, __pad2 = 0, __pad3 = 0,
__flags = 0},
__size = "\000\000\000\000\n", '\0' <repeats 15 times>, "\n", '\0' <repeats 34 times>, __align = 42949672960}
写线程已经在排队了,为什么写线程不能获得锁呢?写锁的优先级不是比读锁高吗?
测试过程中读锁可以抢占写锁,没有出现写锁抢占读锁的情况,请大家给看看我那里理解所了,谢谢先。 |
|