concurrent readers and mutually excluding writers in C using pthreads

自闭症网瘾萝莉.ら 提交于 2020-01-05 07:59:49

问题


I was hoping if someone could forward me or show me a program that has multiple readers yet mutually excluding writers in C. I searched the entire internet for it, and could not find a single example that displays this behavior using coarse-grained locking. I know I can use pthread_rwlock_init, pthread_rwlock_rdlock, etc, I just don know how to use it. I learn by examples, which is why Im here.

Suppose I have a region of code(not a shared variable)and I want multiple reads, yet a single writer, this is what I don't know how to accompolish using pthreads rwlocks. I don't understand how the code will know that now it is being written to, compared to now it is being read. Thanks.


回答1:


You can take a look at page 24 of Peter Chapin's Pthread Tutorial for an example. I added it below.

#include<pthread.h>
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 ;
}


来源:https://stackoverflow.com/questions/15794339/concurrent-readers-and-mutually-excluding-writers-in-c-using-pthreads

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!