Linux多线程编程:线程同步之三--读写锁rwlock

读写锁使用

  1. 当读写锁是“写模式加锁”时,解锁前,所有对该锁加锁的线程都会被阻塞(通俗一点:写完才进行任何操作);
  2. 当读写锁是“读模式加锁”时,如果线程以读模式对其加锁会成功,如果线程以写模式加锁会阻塞;所以相比于读写锁和互斥锁,读线程多时读写锁可以提高访问效率(通俗一点:可以一起读,但读完才能写);
  3. 当读写锁是“读模式加锁”时,既有试图以写模式加锁的线程,也有试图以读模式加锁的线程,那么读写锁会阻塞随后的读模式请求,优先满足写模式锁。也就是说读写同时阻塞时,写模式优先级高
  4. 读写锁也叫共享-独占锁,当读写锁以读模式锁住时,它是以共享模式锁住的;当它以写模式锁住时,它是独占模式锁住的。写独占、读共享

初始化

int  pthread_rwlock_init(pthread_rwlock_t  *restrict  rwlock,  
						 const pthread_rwlockattr_t *restrict attr);

 参数 rwlock 是一个指向读写锁的指针,参数 attr 是一个读写锁属性对象的指针,如果将NULL 传递给它,则使用默认属性来初始化一个读写锁。

销毁读写锁:

int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);

读写锁的常见形式

// 阻塞,一直等到获得锁
int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);

// 非阻塞,成功获得锁返回0,否则返回错误的EBUSY
int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);

// 解锁
int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);

例子

编写测试样例进行验证前面所讲的读写锁的特点(尤其字体加粗部分):

#include 
#include 
#include 
#include 

int count = 0;
pthread_rwlock_t rwlock;

void *reader(void *pvoid)
{
	while(1)
	{
		pthread_rwlock_rdlock(&rwlock);
		printf("========= %s: %d\n", (char*)pvoid, count);
		pthread_rwlock_unlock(&rwlock);
		usleep(4000);

		if(count > 20)
			pthread_exit(NULL);
	}
}

void *writer(void *pvoid)
{
	while(1)
	{
		pthread_rwlock_wrlock(&rwlock);
		printf("+++++++++ %s: %d\n", (char*)pvoid, ++count);
		usleep(2000);
		pthread_rwlock_unlock(&rwlock);
		usleep(2000);

		if(count > 20)
			pthread_exit(NULL);
	}
}

int main(void)
{
	int i;
	pthread_t tid[5];

	pthread_rwlock_init(&rwlock, NULL);

	pthread_create(&tid[0], NULL, reader, "reader0");
	pthread_create(&tid[1], NULL, reader, "reader1");
	pthread_create(&tid[2], NULL, reader, "reader2");
	pthread_create(&tid[3], NULL, writer, "writer0");
	pthread_create(&tid[4], NULL, writer, "writer1");

	for(i = 0; i < 5; i++)
		pthread_join(tid[i], NULL);

	pthread_rwlock_destroy(&rwlock);

	return 0;
}

部分输出结果:

========= reader0: 0
========= reader2: 0
========= reader1: 0
+++++++++ writer0: 1
+++++++++ writer1: 2
+++++++++ writer0: 3
+++++++++ writer1: 4
+++++++++ writer0: 5
+++++++++ writer1: 6
+++++++++ writer0: 7
+++++++++ writer1: 8
========= reader0: 8
========= reader2: 8
========= reader1: 8
+++++++++ writer0: 9
+++++++++ writer1: 10

你可能感兴趣的:(Linux)