相关API
初始化读写锁
#include <pthread.h>
/**
* [pthread_rwlock_init 初始化读写锁]
* @param rwlock [初始化读写锁的地址]
* @param attr [读写锁的属性]
* @return [成功返回0,失败返回错误号]
*/
int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock,
const pthread_rwlockattr_t *restrict attr);
pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
释放读写锁
#include <pthread.h>
int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);
获取读锁
#include <pthread.h>
/**
* [pthread_rwlock_rdlock
以阻塞方式在读写锁上获取读锁(读锁定)。
如果没有写者持有该锁,并且没有写者阻塞在该锁上,则调用线程会获取读锁。
如果调用线程未获取读锁,则它将阻塞直到它获取了该锁。
一个线程可以在一个读写锁上多次执行读锁定。线程可以成功调用 pthread_rwlock_rdlock() 函数 n 次,但是之后该线程必须调用pthread_rwlock_unlock() 函数 n 次才能解除锁定。
]
* @param rwlock [读写锁]
* @return [成功返回0,失败返回错误号]
*/
int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
/**
* [pthread_rwlock_tryrdlock
* 用于尝试以非阻塞的方式来在读写锁上获取读锁。
如果有任何的写者持有该锁或有写者阻塞在该读写锁上,则立即失败返回
]
* @param rwlock [读写锁]
* @return [成功返回0,失败返回错误号]
*/
int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);
获取写锁
#include <pthread.h>
/*
功能:在读写锁上获取写锁(写锁定)。
如果没有写者持有该锁,并且没有写者读者持有该锁,则调用线程会获取写锁。
如果调用线程未获取写锁,则它将阻塞直到它获取了该锁。
*/
int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
/*
功能:用于尝试以非阻塞的方式来在读写锁上获取写锁。
如果有任何的读者或写者持有该锁,则立即失败返回。
*/
int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);
解锁
#include <pthread.h>
/*
用于释放读锁和写锁
*/
int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
实例
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
pthread_rwlock_t rwlock;/* 定义读写锁变量 */
char buf[] = "0123456789";
/* 定义数组元素输出子线程执行函数 */
void *prt_arr(void *arg)
{
int i = *(int *)arg;
while(1)
{
/* 获取读锁 */
pthread_rwlock_rdlock(&rwlock);
printf("%d,%s\n", i, buf);
/* 释放锁 */
pthread_rwlock_unlock(&rwlock);
sleep(1);
}
}
/* 定义数组元素倒序子线程执行函数 */
void *reverse_arr(void *arg)
{
int i;
char tmp;
while(1)
{
/* 获取写锁 */
pthread_rwlock_wrlock(&rwlock);
for (i = 0; i < 5; i++)
{
tmp = buf[i];
buf[i] = buf[9 - i];
buf[9 - i] = tmp;
}
/* 释放锁 */
pthread_rwlock_unlock(&rwlock);
}
}
int main()
{
int i;
int ret;
pthread_t prt_id;
pthread_t reverse_id;
/* 初始化读写锁 */
pthread_rwlock_init(&rwlock, NULL);
for (i = 0; i < 10; i++)
{
int num = i;
ret = pthread_create(&prt_id, NULL, prt_arr, &num);
if (ret != 0)
{
fprintf(stderr, "create video pthread fail\n");
return -1;
}
sleep(1);
}
ret = pthread_create(&reverse_id, NULL, reverse_arr, NULL);
if (ret != 0)
{
fprintf(stderr, "create video pthread fail\n");
return -1;
}
while(1)
{
printf("main pthread\n");
sleep(10);
}
/* 销毁读写锁 */
pthread_rwlock_destroy(&rwlock);
}
网友评论