Readers and Writers

Source: Internet
Author: User

**************************************** ******************************************************

Original works, from the "Xiaofeng residual month xj" blog, welcome to reprint, reprint please be sure to indicate the source (http://blog.csdn.net/xiaofengcanyuexj ).

For various reasons, there may be many shortcomings. Thank you!

******************************************************* **************************************** **********

In the process of multi-threaded programming, synchronization and mutex between threads are the key points to be carefully considered. Readers and writers are typical examples of synchronization between threads: several readers read articles and several writers edit articles at the same time to ensure that multiple readers and multiple writers can concurrently or concurrently (the differences between parallelism and concurrency and some basic concepts of multithreaded programming, you can refer to this blog post: multithreading preliminary) execution. A typical solution for readers and writers is to set up an article buffer, and then multiple readers and writers access the buffer simultaneously or jointly. Write operations are exclusive locks (excluding readers and other writers), and read operations are shared locks (multiple readers can read and reject writers ). Of course, when the reader and writer, writer and writer arrive at almost the same time, priority allocation is involved, which should also be considered.

1. Model Analysis

     The feature of the reader and writer problem is that the reader does not change the number of buffers, and multiple readers can read the buffer information at the same time. The writer, writer, and reader can only access the same data in the buffer zone at the same time. Any writer may involve read/write conflicts, that is, data competition. Multiple readers can access the same data item at the same time. For the same data item, multiple writers or writers cannot access the same data item at the same time. For different data items, all read/write access can be performed simultaneously. We should try to improve efficiency, reduce the lock range, and avoid read/write conflicts caused by data competition.

The post section describes the source code of the reader's problem Model. The following describes the synchronization and mutex operations for a single storage unit in the buffer zone. To process multiple units, replace int type with set type.

Int count_Reader = 0; int mutex = 1; int WriterSemaphore = 1; Reader {while (ture) {p (mutex); if (0 = count_Reader) p (WriterSemaphore ); ++ count_Reader; v (mutex); perform read operations; p (mutex); if (1 = count_Reader) v (WriterSemaphore); -- count_Reader; v (mutex );}} writer {while (true) {p (WriterSemaphore); write operation v (WriterSemaphore );}}

The above introduces atomic operations p and v to achieve synchronization and mutual exclusion.


2. Source code

The lower-layer Lock and Condition classes in Java are not well understood, and Java is better than CriticalSection and Event encapsulation in C ++, therefore, you cannot find a more efficient method. You can only paste the Java code that calls the ReadWriteLock interface:

/*** ReaderAndWriter. java * Copyright 2014.11.6 XuJin **/import java. util. list; import java. util. arrayList; import java. util. concurrent. locks. lock; import java. util. concurrent. locks. readWriteLock; import java. util. concurrent. locks. reentrantReadWriteLock; class Artical {private static int m_nReaderCount = 0; private static int m_nWriterCount = 0; private ReadWriteLock lock = new ReentrantReadWriteLock (); private Lock readLock = lock. readLock (); private Lock writerLock = lock. writeLock (); private String m_strName; private int m_nId; public Artical (String name, int id) {m_strName = name; m_nId = id;} public String getName () {readLock. lock (); int seq = ++ m_nReaderCount; System. out. println ("no." + seq + ""); String strRetValue; try {// read operation strRetValue = m_strName; System. out. println ("reader reads number" + m_nId + ", content:" + strRetValue); try {Thread. sleep (500);} catch (InterruptedException e) {e. printStackTrace () ;}} finally {System. out. println ("no." + seq + ""); readLock. unlock ();} return strRetValue;} public void setName (String name) {writerLock. lock (); int seq = ++ m_nWriterCount; System. out. println ("no." + seq + "writer start"); try {// write operation m_strName = name; System. out. println ("writer edits" + m_nId + ", content:" + m_strName); try {Thread. sleep (500);} catch (InterruptedException e) {e. printStackTrace () ;}} finally {System. out. println ("nth" + seq + "writer End"); writerLock. unlock () ;}} class ArticalBuffer {private List <Artical> m_ArrArticalBuffer; public ArticalBuffer () {m_ArrArticalBuffer = new ArrayList <Artical> ();} public String getArtical (int id) {String retValue = null; if (id <m_ArrArticalBuffer.size () retValue = m_ArrArticalBuffer.get (id ). getName (); return retValue;} public void setArtical (int id, String name) {if (id <m_ArrArticalBuffer.size () {Artical art = m_ArrArticalBuffer.get (id); art. setName (name) ;}} public void addArtical (String name) {m_ArrArticalBuffer.add (new Artical (name, m_ArrArticalBuffer.size ();} class Reader extends Thread {ArticalBuffer m_ArticalBuffer; public Reader (ArticalBuffer pro) {m_ArticalBuffer = pro;} public void run () {int id = (int) (Math. random () * 4); m_ArticalBuffer.getArtical (id) ;}} class Writer extends Thread {ArticalBuffer m_ArticalBuffer; public Writer (ArticalBuffer pro) {m_ArticalBuffer = pro;} public void run () {int id = (int) (Math. random () * 4); String name = "XuJin"; m_ArticalBuffer.setArtical (id, name) ;}} public class ReaderAndWriter {public static void main (String [] agrs) {String m_strName [] = {"Alice", "Bob", "Green", "Dell", "Marry", "Jim", "John", "Kobe ", "James", "Wed", "Paul"}; ArticalBuffer artBuffer = new ArticalBuffer (); for (int I = 0; I <m_strName.length; ++ I) {artBuffer. addArtical (m_strName [I]);} Reader [] readerSet = new Reader [20]; for (int I = 0; I <20; ++ I) {readerSet [I] = new Reader (artBuffer); readerSet [I]. start ();} Writer [] writerSet = new Writer [5]; for (int I = 0; I <5; ++ I) {writerSet [I] = new Writer (artBuffer); writerSet [I]. start ();}}}


3. Note

1) Lock replaces the use of the synchronized keyword, and Condition replaces the use of the Object monitor method (wait, policy, and policyall;

2) ReadWriteLock maintains a pair of read/write locks for read-only or write operations respectively. Compared with mutex lock, read-write lock allows more advanced concurrent access to shared data. Although only one writer thread can modify shared data at a time, in many cases, any number of threads can simultaneously read shared data (reader thread ), read-Write locks take advantage of this. Theoretically, compared with mutex locks, the increased concurrency allowed by Read-write locks will lead to greater performance improvement. In practice, Concurrency can be fully enhanced only when the access mode is applicable to shared data on a multi-processor. Therefore, compared with mutex lock, whether read-write lock can improve performance depends on the frequency of reading data during read/write operations relative to the frequency of modifying data, and data contention-that is, the number of threads trying to read or write the data at the same time.



Due to limited time, I have referenced some documents during the blog writing process and would like to express my gratitude. In addition, you may have some shortcomings due to the level. Thank you!


Readers and Writers

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.