问题
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