Linux 线程同步2

线程同步2


读写锁

读写锁与互斥锁类似,不过读写锁允许更高的并行性。读写锁可以有三种状态:(1) 读模式下的加锁状态;(2)写模式下的加锁状态(3)不加锁状态。这个区别与互斥锁的,因为互斥锁只有加锁和不加锁的两种状态。一次只能有一个线程的写状态的读写锁,但是可以有多个线程占有读状态的读写锁。

初始化和清理

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

int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);

功能

读写锁通过调用pthread_rwlock_init进行初始化的,attr =NULL时使用缺省的属性。在释放读写锁占用的内存之前,需要调用pthread_rwlock_destroy函数做清理工作。

加锁和解锁


#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);  //无论那种模式都可以用的解锁


unix环境高级编程的例子

//使用读写锁
#include 
#include 

struct job
{
	struct job *j_next;
	struct job *j_prev;
	pthread_t j_id;
};

struct queue
{
	struct job *q_head;
	struct job *q_tail;
	pthread_rwlock_t q_lock;
};

int queue_init(struct queue *qp)
{
	int err;

	qp->q_head = NULL;
	qp->q_tail = NULL;
	err= pthread_rwlock_init(&qp->q_lock, NULL);

	if(err != 0)
	{
		return(err);
	}

	return(0);
}

void job_insert(struct queue *qp, struct job *jp)
{
	pthread_rwlock_wrlock(&qp->q_lock);
	jp->j_next = qp->q_head;
	jp->j_prev = NULL;
	if(qp->q_head != NULL)
	{
		qp->q_head->j_prev = jp;
	}
	else
	{
		qp->q_tail = jp;
	}

	qp->q_head = jp;
	pthread_rwlock_unlock(&qp->q_lock);
}

void job_append(struct queue *qp, struct job *jp)
{
	pthread_rwlock_wrlock(&qp->q_lock);
	jp->j_next = NULL;
	jp->j_prev = qp->q_tail;
	if(qp->q_tail != NULL)
	{
		qp->q_tail->j_next = jp;
	}
	else
	{
		qp->q_head = jp;
	}
	qp->q_tail = jp;
	pthread_rwlock_unlock(&qp->q_lock);
}

void job_remove(struct queue *qp,struct job *jp)
{
	pthread_rwlock_wrlock(&qp->q_lock);
	if(jp == qp_q_head)
	{
		qp->q_head = jp->next;
		if(qp->q_tail == jp)
		{
			qp->q_tail = NULL;
		}
	}
	else if(jp == qp->q_tail)
	{
		qp->q_tail = jp->j_prev;
		if(qp->q_head == jp)
		{
			qp->q_head = NULL;
		}
	}
	else
	{
		jp->j_prev->j_next = jp->j_next;
		jp->j_next->j_prev = jp->j_prev;
	}
	pthread_rwlock_unlock(&qp->q_lock);
}

struct job *job_find(struct queue *qp, pthread_t id)
{
	struct job *jp;

	if(pthread_rwlock_rdlock(&qp->q_lock) != 0)
	{
		return(NULL);
	}

	for(jp = qp->q_head; jp != NULL; jp = ip->j_next)
	{
		if(pthread_equal(jp->j_id, id))
		{
			break;
		}
	}
	pthread_rwlock_unlock(&qp->q_lock);
	return(jp);
}


你可能感兴趣的:(linux,Linux环境编程)