Reader writer problem of multi-thread synchronization

Source: Internet
Author: User

Problem definition:

Existing piece of shared memory, multiple read processes, and multiple write processes. Multiple read processes can be read at the same time, but no other read or write processes are executed when there is a write process in progress.

There are 3 variants of the problem. The first is called "Reader First" (readers-preference). In this case, as long as there is a process in the read, the write process has to wait.

The implementation is as follows:

#include <stdio.h>#include<stdlib.h>#include<pthread.h>#defineM 6//Number of readers#defineN 2//Number of writersintReadcount =0;//Current number of readerspthread_mutex_t mutex = Pthread_mutex_initializer;//for mutually exclusive modifications to the Readcount variablepthread_mutex_t RW = pthread_mutex_initializer;//for mutual exclusion between reading, writing, and writing and writingvoid* Write (void*Arg) {Pthread_mutex_lock (&rw); printf ("writer%d is writing\n", ARG); Sleep (1); printf ("writer%d is leaving\n", ARG); Pthread_mutex_unlock (&rw);}void* Read (void*Arg) {Pthread_mutex_lock (&mutex); if(Readcount = =0) Pthread_mutex_lock (&rw); ++Readcount; Pthread_mutex_unlock (&mutex); printf ("Reader%d is reading\n", ARG); Sleep (1); printf ("Reader%d is leaving\n", ARG); Pthread_mutex_lock (&mutex); --Readcount; if(Readcount = =0) Pthread_mutex_unlock (&rw); Pthread_mutex_unlock (&mutex);}intMain () {pthread_t readers[m], writers[n]; inti;  for(i =0; i < M; ++i) pthread_create (&readers[i], NULL, read, (void*) (i);  for(i =0; i < N; ++i) pthread_create (&writers[i], NULL, write, (void*) (i); Sleep (Ten); return 0;}

In this case, it is easy to cause the writer to starve.

Reader writer problem of multi-thread synchronization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.