并发读者并使用pthreads在C中相互排除编写者

我希望有人能转发我或向我展示一个程序,该程序有多个读者,但相互排除C中的编写者。我在整个互联网上搜索它,并且找不到使用粗粒度锁定显示此行为的单个示例。 我知道我可以使用pthread_rwlock_init,pthread_rwlock_rdlock等,我只是不知道如何使用它。 我通过例子学习,这就是为什么我在这里。

假设我有一个代码区域(不是共享变量),我想要多个读取,但是只需要一个编写器,这就是我不知道如何使用pthreads rwlocks进行同步。 我不明白代码将如何知道现在正在编写,与现在正在阅读相比。 谢谢。

您可以查看Peter Chapin的Pthread教程第24页的示例。 我在下面添加了它。

#include int shared; pthread_rwlock_t lock ; void∗ thread_function (void∗ arg) { pthread_rwlock_rdlock (&lock); //Read from the shared resource. pthread_rwlock_unlock(&lock); } void main( void ) { pthread_rwlock_init(&lock, NULL); // Start threads here. pthread_rwlock_wrlock(& lock ); // Write to the shared resource . pthread_rwlock_unlock(&lock); // Join_with threads here . pthread_rwlock_destroy(&lock); return 0 ; }