When writing multithreading, there is a situation that is more common. That is, there are fewer opportunities for public data modification . Rather than rewrite, they read more opportunities.
Reader-writer mode: Three relationships, two types of people, one place
Three types of relationships:
Readers and readers: no relationship
Written and written by: mutual exclusion
Reader and Writer: synchronization and mutual exclusion
Two types of people: Reader, writer
One place: the same critical resource (data)
Spin Lock: If the waiting condition is not satisfied, does not hang, always apply for the lock. It is appropriate for a thread to occupy a shorter lock time.
When there are more and more readers ready to read, if there is a writer arrives, at this time should be the current reader after reading, improve the writer priority, the next entry into the critical section is the writer. ---------Write is preferable, otherwise it will cause the writer to starve.
When there are more than one writer ready to write, if a reader arrives, at this time should be the current writer after writing, improve the reader priority, the next entry into the critical section is the reader. ---------readers first, otherwise it will cause the reader to starve
Read-write lock correlation function:
#include <pthread.h>
int Pthread_rwlock_destroy (pthread_rwlock_t *rwlock);
int Pthread_rwlock_init (pthread_rwlock_t *restrict Rwlock,
Const pthread_rwlockattr_t *restrict attr);
int Pthread_rwlock_trywrlock (pthread_rwlock_t *rwlock);
int Pthread_rwlock_wrlock (pthread_rwlock_t *rwlock);//write First
int Pthread_rwlock_rdlock (pthread_rwlock_t *rwlock);//Reader preference
int Pthread_rwlock_tryrdlock (pthread_rwlock_t *rwlock);
#include <stdio.h> #include <pthread.h>int g_val=0;pthread_rwlock_t rw_lock;void* Reader (Void* arg) { while (1) { pthread_rwlock_rdlock (&rw_lock); printf (" G_val: %d\n ", g_val); pthread_rwlock_unlock (&rw_lock); }}void* writer (Void* arg) { while (1) { sleep (1);//enable the writer to compete once every second lock resources pthread_rwlock_wrlock (&rw_lock); g_val++; pthread_rwlock_unlock (&rw_lock); }} Int main () { pthread_t tid1,tid2; pthread_rwlock_init ( &rw_lock,null); pthread_create (&tid1,null,reader,null); pthread_create ( &tid2,null,writer,null); pthread_rwlock_destroy (&rw_lock); pthread_join (Tid1,null); pthread_join (tid2,null); return 0;}
This article is from the "Small Stop" blog, please be sure to keep this source http://10541556.blog.51cto.com/10531556/1767269
Reader writer mode