分类: LINUX
2013-06-05 14:46:27
原文地址:(3)读写锁 作者:g_programming
读写锁:
在编译时必须是类似的语句:gcc -o test test.c -D_XOPEN_SOURCE=500 –lpthread
定义:pthread_rwlock_t
初始化,销毁:
#include
int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock,
const pthread_rwlockattr_t *restrict attr);
int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);
Both return: 0 if OK, error number on failure
执行读写锁:
include
int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);
All return: 0 if OK, error number on failure
注意:对于读写锁一次只有一个线程占有一个写模式的读写锁,可以有多个线程拥有读模式的读写锁。
例程1:(注意程序可以同时读一个处以读模式下的读写锁)
#include
#include
#include
#include
pthread_rwlock_t flock;
char buf[512];
char str[4][30] = {"aaaaaaaaaaaaaaaaaaaa\n","bbbbbbbbbbbbbbbbbbbb\n",
"cccccccccccccccccccc\n","dddddddddddddddddddd\n"};
void *
thr_fn1(void *arg)
{
long i;
for(i=0;i<2000000;i++)
{
pthread_rwlock_wrlock(&flock);
strcpy(buf,str[i%4]);
pthread_rwlock_unlock(&flock);
}
}
void *
thr_fn2(void *arg)
{
int i;
for(i=0;i<10;i++)
{
pthread_rwlock_rdlock(&flock);
printf("thead 2 :%s", buf);
pthread_rwlock_unlock(&flock);
usleep(5);
}
}
void *
thr_fn3(void *arg)
{
int i;
for(i=0;i<10;i++)
{
pthread_rwlock_rdlock(&flock);
printf("thead 3 :%s", buf);
pthread_rwlock_unlock(&flock);
usleep(5);
}
}
int main()
{
pthread_t tid1,tid2,tid3;
int err;
strcpy(buf,"hello,world!\n");
pthread_rwlock_init(&flock,NULL);
err=pthread_create(&tid1,NULL,thr_fn1,NULL);
if(err!=0)
printf("can't create thread 1:%s\n",strerror(err));
err=pthread_create(&tid2,NULL,thr_fn2,NULL);
if(err!=0)
printf("can't create thread 2:%s\n",strerror(err));
err=pthread_create(&tid3,NULL,thr_fn3,NULL);
if(err!=0)
printf("can't create thread 3:%s\n",strerror(err));
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_join(tid3,NULL);
pthread_rwlock_destroy(&flock);
return 0;
}
程序结果:
thead 2 :cccccccccccccccccccc
thead 3 :cccccccccccccccccccc
thead 2 :cccccccccccccccccccc
thead 3 :cccccccccccccccccccc
thead 2 :dddddddddddddddddddd
thead 3 :dddddddddddddddddddd
thead 2 :dddddddddddddddddddd
thead 3 :dddddddddddddddddddd
thead 2 :dddddddddddddddddddd
thead 3 :dddddddddddddddddddd
thead 2 :dddddddddddddddddddd
thead 3 :dddddddddddddddddddd
thead 2 :dddddddddddddddddddd
thead 3 :dddddddddddddddddddd
thead 2 :dddddddddddddddddddd
thead 3 :dddddddddddddddddddd
thead 2 :dddddddddddddddddddd
thead 3 :dddddddddddddddddddd
thead 2 :dddddddddddddddddddd
thead 3 :dddddddddddddddddddd