读写锁与互斥量类似,不过读写锁的并行性更高。

读写锁可以有三种状态:(1)读模式加锁;(2)写模式加锁;(3)不加锁。

在写加锁状态时,在解锁之前,所有试图对这个锁加锁的线程都会被阻塞。在读加锁状态时,所有试图以读模式对它进行加锁的线程都可以得到访问权限。但是如果线程希望以写模式加锁,它必须阻塞,直至所有的线程释放读锁。

读写锁很适合于对数据结构读的次数远大于写的情况。


相关函数:

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

int pthread_rwlock_destroy(pthread_rwlock_t *rwlock)  // 成功则返回0,失败则返回错误代码

int pthread_rwlock_rdlock(pthread_rwlock_t *restrict rwlock) ;//读模式加锁

int pthread_rwlock_wrlock(pthread_rwlock_t *restrict rwlock);//写模式加锁

int pthread_rwlock_unlock(pthread_rwlock_t *restrick rwlock);

int pthread_rwlock_tryrdlock(pthread_rwlock_t *restrict rwlock);

int pthread_rwlock_trywrlock(pthread_rwlock_t *restrict rwlock);

int pthread_rwlock_trywrlock(pthread_rwlock_t *restrict rwlock);

相关示例:读者写者问题,这也是一个很经典的多线程题目,题目大意:有一个写者多个读者,多个读者可以同时读文件,但写者在写文件时不允许有读者在读取文件,同样有读者读文件时,不允

#include <stdio.h>
#include <pthread.h>

#define Read_Num 2

pthread_rwlock_t lock;

class Data
{
	public:
		Data(int i, float f): I(i),F(f)
			{}
	private:
		int I;
		float F;
			
};

Data *pdata = NULL;


void *read(void * arg)
{
	int id = (int)arg;
	while(true)
		{
	
			pthread_rwlock_rdlock(&lock);
			printf(" reader %d is reading data!\n", id);
			if(data == NULL)
				{
					printf("data is NULL\n");
				}
			else
				{
					printf("data: I = %d, F = %f \n", pdata->I, pdata->F);
				}
				pthread_rwlock_unlock(&lock);
		}
	
	pthread_exit(0);
	
}

void *write()
{
	while(true)
		{
			pthread_rwlock_wrlock(&lock);
			printf(" writer is writind data!\n");
			if(pdata == NULL)
				{
					pdata = new Data(1, 1.1);
					printf("Writer is writing data: %d, %f\n", pdata->I, pdata->F);
				}
			else
				{
					delete pdata;
					pdata = NULL;
					printf("writer free the data!");
				}

			pthread_rwlock_unlock(&lock);
		}
	pthread_exit(0);
}
	

void main()
{
	pthread_t reader[Read_Num];
	pthread_t writer;

	for(int i = 0;i<Read_Num;i++)
		{
			pthread_create(&read[i],NULL,read,(void *)i);
		}

	pthread_create(writer, NULL, write, NULL);

	sleep(1);
	return 0;
}

许写者写文件。



Logo

更多推荐