网站购物车建设,外链在线生成,wordpress导入doc,售后网站用什么模板pthread 读写锁使用
读写锁#xff1a;提供了一种高效的机制来控制对共享资源的访问。允许多个线程同时读取共享资源#xff0c;但只允许一个线程独占地写入访问。适用于读取远远超过写入的场景下#xff0c;因为写入操作需要独占地访问资源#xff0c;可能会影响读取操作…pthread 读写锁使用
读写锁提供了一种高效的机制来控制对共享资源的访问。允许多个线程同时读取共享资源但只允许一个线程独占地写入访问。适用于读取远远超过写入的场景下因为写入操作需要独占地访问资源可能会影响读取操作的性能。
pthread_rwlock_init 函数原型 int pthread_rwlock_init(pthread_rwlock_t *rwlock, const pthread_rwlockattr_t *attr);rwlock指向要初始化的读写锁对象的指针。attr可选的指向读写锁属性对象的指针可以为 NULL。返回值成功返回 0失败返回错误代码。 用于初始化读写锁对象。 使用读写锁时应该先初始化再使用最后再销毁。
pthread_rwlock_destroy 函数原型 int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);rwlock指向要销毁的读写锁对象的指针。 用于销毁一个读写锁对象释放相关的资源。 销毁读写锁之前要确保没有任何线程正在持有该读写锁否则会导致未定义的结果。
pthread_rwlock_rdlock 函数原型 int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);rwlock: 指向要获取的读写锁对象的指针。 用于获取读取锁。如果当前没有其他线程持有该锁对象的写入锁则该函数成功返回0并立即返回否则该函数将阻塞等待直到写入操作完成并且当前线程可以安全地读取共享资源。 允许多个线程同时读取共享资源但不允许写入操作。
pthread_rwlock_rwlock 函数原型 int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);rwlock: 指向要获取的读写锁对象的指针。 用于获取写入锁如果当前没有其他线程持有该锁对象的任何锁则该函数成功返回0并立即返回否则该函数将阻塞等待直到其他线程释放该锁然后当前线程可以独占地修改共享资源。
pthread_rwlock_unlock 函数原型 int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);rwlock: 指向要释放的读写锁对象的指针。 释放指定的读写锁对象的读取锁或写入锁。如果当前线程没有持有该锁则该函数的行为是未定义的。
示例 以下示例演示了两个线程同时读取一个变量一个线程独占地修改变量 #include stdio.h
#include string.h
#include pthread.hpthread_rwlock_t g_rwlock;void* thread1_func(void* arg)
{int *var (int*)arg;// 获取读取锁pthread_rwlock_rdlock(g_rwlock);printf(thread1 read var is %d\n, *var);// 释放读取锁pthread_rwlock_unlock(g_rwlock);return NULL;
}void* thread2_func(void* arg)
{int *var (int*)arg;// 获取读取锁pthread_rwlock_rdlock(g_rwlock);printf(thread2 read var is %d\n, *var);// 释放读取锁pthread_rwlock_unlock(g_rwlock);return NULL;
}void* thread3_func(void* arg)
{int *var (int*)arg;// 获取写入锁pthread_rwlock_wrlock(g_rwlock);*var 100;printf(thread3 write var is %d\n, *var);// 释放写入锁pthread_rwlock_unlock(g_rwlock);return NULL;
}int main()
{// 初始化读写锁pthread_rwlock_init(g_rwlock, NULL);// 创建线程int var 10;pthread_t th1;pthread_t th2;pthread_t th3;pthread_create(th1, NULL, thread1_func, var);pthread_create(th2, NULL, thread2_func, var);pthread_create(th3, NULL, thread3_func, var);// 等待线程结束pthread_join(th1, NULL);pthread_join(th2, NULL);pthread_join(th3, NULL);// 销毁读写锁pthread_rwlock_destroy(g_rwlock);return 0;
}