c++ - pthread读写锁是先进先出的吗?

标签 c++ multithreading pthreads readwritelock

pthread.h中是pthread_rwlock_t FIFO吗?

在下面的示例中,我们有多个线程。想象一下,每个线程都保证按顺序运行。

// Thread 1 - does a write lock
pthread_rwlock_wrlock(&lock);

// Thread 2 - does a read but has to wait for 1
pthread_rwlock_rdlock(&lock);

// Thread 3 - does a read but has to wait for 1
pthread_rwlock_rdlock(&lock);

// Thread 4 - does a write but has to wait for 1
pthread_rwlock_wrlock(&lock);

// Thread 1 - unlocks
pthread_rwlock_unlock(&lock);

// who gets the lock?

线程1释放锁后,谁获得锁?线程2和线程3能保证吗?或者可以给4吗?

再次想象一下,每个线程都保证按顺序运行,并且线程 1 在所有线程都尝试获取锁之前不会释放锁。

最佳答案

我做了一些研究,发现this document from the Oracle website这解释了pthread读写锁的调度策略。

If the call to the pthread_rwlock_unlock() results in the read-write lock object becoming unlocked and there are multiple threads waiting to acquire the read-write lock object for writing, the scheduling policy is used to determine which thread acquires the read-write lock object for writing. If there are multiple threads waiting to acquire the read-write lock object for reading, the scheduling policy is used to determine the order in which the waiting threads acquire the read-write lock object for reading. If there are multiple threads blocked on rwlock for both read locks and write locks, it is unspecified whether the readers acquire the lock first or whether a writer acquires the lock first.

所以总而言之,它们不能保证是先进先出的。

关于c++ - pthread读写锁是先进先出的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43464515/

相关文章:

c++ - C++线程中的段错误

c - 如果条件变量向锁定的线程发出信号怎么办?

Linux Pthreads 用户级或内核级

c++ - 什么是好的游戏随机数生成器?

c - 使用 pthread_create() 时将结构作为参数传递

c++ - Qt Creator - 无法将信号连接到插槽(没有匹配的调用功能)

c++ - 错误 C2064 : term does not evaluate to a function taking 1 arguments - something about threads

java - 如何正确处理来自 ListenableFuture guava 的异常?

c++ - 根据其中的数字子字符串拆分字符串

c++ - OpenGL 中的压缩纹理批处理