Multithreaded Programming Example 4 (writer reader question)

Source: Internet
Author: User
Tags semaphore

Reader writer is also a very well-known synchronization problem.

The reader writer's question description is very simple, there is a writer many readers, multiple readers can read the file at the same time, but the writer does not allow readers to write the file, the reader is also reading the file when the writer does not go to write files.

#pragmaOnce#define_crtdbg_map_alloc#include<cstdio>#include<Windows.h>#include<crtdbg.h>#include<process.h>intCurrreadernum =0;Const intReadernum =5;//critical segments and eventscritical_section Cs,cs_readernum; HANDLE G_heventwriter, G_heventnoreader;//Setting the console output colorBOOL Setconsolecolor (WORD wattributes) {HANDLE hconsole=GetStdHandle (Std_output_handle); if(Hconsole = =Invalid_handle_value) {        return false; }    returnSetconsoletextattribute (Hconsole, wattributes);}//Reader thread output functionvoidReaderprintfun (Char*sz, ...)    {va_list parglist;    Va_start (Parglist, SZ); EnterCriticalSection (&CS);    Setconsolecolor (Foreground_green);    vfprintf (stdout, SZ, parglist); LeaveCriticalSection (&CS); Va_end (parglist);}//writer thread output functionvoidWriteprintfun (Char*SZ) {EnterCriticalSection (&CS);    Setconsolecolor (foreground_red); printf ("%s\n", SZ); LeaveCriticalSection (&CS);}//Reader Thread FunctionsUnsignedint_stdcall Readerthreadfun (PVOID pM) {Readerprintfun ("the reader with number%d enters the waiting ... \ n", GetCurrentThreadID ()); //wait for the writer to finishWaitForSingleObject (G_heventwriter, INFINITE); //Increased number of readersEnterCriticalSection (&cs_readernum); ++Currreadernum; if(1==currreadernum)    {resetevent (G_heventnoreader); } leavecriticalsection (&cs_readernum); //Read FileReaderprintfun ("readers with number%d begin to read files ... \ n", GetCurrentThreadID ()); Sleep (rand ()% -); //end of Reading, the number of readers decreasedReaderprintfun ("reader with number%d ends reading file ... \ n", GetCurrentThreadID ()); //reduced number of readersEnterCriticalSection (&cs_readernum); --Currreadernum; if(0==currreadernum)    {SetEvent (G_heventnoreader); } leavecriticalsection (&cs_readernum); return 0;}//Writer thread functionsUnsignedint_stdcall Writethreadfun (PVOID pM) {Writeprintfun ("The writer thread enters the waiting ..."); //the reader waiting to read the file is zeroWaitForSingleObject (G_heventnoreader, INFINITE); //Mark Writer is writing fileresetevent (G_heventwriter); Writeprintfun ("The writer begins to write the file ..."); Sleep (rand ()% -); Writeprintfun ("write end Write file"); //mark writer End Write fileSetEvent (G_heventwriter); return 0;}intMain () {printf ("reader Writer's question \ n"); //initializing events and semaphoresInitializeCriticalSection (&msg; InitializeCriticalSection (&cs_readernum); //manual position, triggeredCurrreadernum =0; G_heventwriter=CreateEvent (NULL, True, true, null); G_heventnoreader=CreateEvent (null, FALSE, TRUE, NULL); size_t I=0; HANDLE Handle[readernum+1];  for(i =1; I <3; i++) {Handle[i]= (HANDLE) _beginthreadex (NULL,0, Readerthreadfun, NULL,0, NULL); }    //the writer thread, which is placed here to prevent the writer from writing the file, then reads sequentially ... )handle[0] = (HANDLE) _beginthreadex (NULL,0, Writethreadfun, NULL,0, NULL); Sleep ( -); //start the rest of the reader thread     for(; i < Readernum +1; i++) {Handle[i]= (HANDLE) _beginthreadex (NULL,0, Readerthreadfun, NULL,0, NULL); } waitformultipleobjects (Readernum+1, handle, TRUE, INFINITE);  for(i =0; I < Readernum +1; i++) {CloseHandle (handle[i]); }    //destroying events and semaphoresCloseHandle (G_heventwriter);    CloseHandle (G_heventnoreader); DeleteCriticalSection (&CS); DeleteCriticalSection (&cs_readernum); //Detecting Memory leaks_CrtDumpMemoryLeaks (); return 0;}

I was thinking about whether to use the semaphore, and later to see http://blog.csdn.net/morewindows/article/details/7596034

Think that the use of events is quite good, the key is to multi-threaded specific scenarios for analysis.

If you use the semaphore here, it will be more cumbersome to handle.

Operation Result:

This problem can also be solved by reading and writing lock Srwlock:

Acquiresrwlockexclusive and releasesrwlockexclusive are called on the writer thread;

The amount of code can be greatly simplified when the reader thread calls acquiresrwlockshared and releasesrwlockshared.

Multithreaded Programming Example 4 (writer reader question)

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.