Second-kill multithreading 11th reader Writer's question

Source: Internet
Author: User

As with the producer consumer Problem of the second multi-threaded tenth producer consumer problem, reader writer is also a very famous 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.

Above is the reader's question, similar to the analysis process of producer consumer problems, first to find out what is a "waiting" situation.

First The writer has to wait until there is no reader to write the file.

Second All readers have to wait for the writer to finish writing the file before they can read the file.

After looking for a "wait" situation, then see if there are any resources to mutually exclusive access. Since there is only one writer and the reader is able to share the read file, there is no resource that requires mutually exclusive access according to the topic. Similar to the beautiful color output in the previous article, we color-set the producer output code (see "VC Console color Settings" in the console output color settings). Therefore, there is a mutually exclusive access here, or it is likely that the reader thread will have output before the writer thread restores the console color settings. Therefore, to make a mutually exclusive access to the output statement, the modified reader and the writer's output functions are as follows:

[CPP]View PlainCopy
  1. Reader thread output function
  2. void readerprintf (char *pszformat, ...)
  3. {
  4. va_list parglist;
  5. Va_start (Parglist, Pszformat);
  6. EnterCriticalSection (&g_cs);
  7. vfprintf (stdout, Pszformat, parglist);
  8. LeaveCriticalSection (&g_cs);
  9. Va_end (parglist);
  10. }
  11. Writer thread output function
  12. void writerprintf (char *pszstr)
  13. {
  14. EnterCriticalSection (&g_cs);
  15. Setconsolecolor (Foreground_green);
  16. printf ("%s\n", pszstr);
  17. Setconsolecolor (foreground_red | Foreground_green | Foreground_blue);
  18. LeaveCriticalSection (&g_cs);
  19. }

The variable parameters used by the reader thread output function are described in using variable parameters in c,c++.

Resolves the mutex output problem and then considers how to implement the synchronization problem. You can set a variable to record the number of readers who are reading the file, and the first reader to begin reading the file will be responsible for closing the sign that allows the writer to enter, and the last reader to end the reading will be responsible for opening the sign that allows the writer to enter it. So the first kind of "wait" situation is solved. The second "Wait" situation is when a writer enters, so the reader cannot enter, and the task can be accomplished with an event--all readers are waiting for the event and the writer is responsible for triggering the event and setting the event as not triggered. See the code in detail for comments:

[CPP]View PlainCopy
  1. Reader and writer questions
  2. #include <stdio.h>
  3. #include <process.h>
  4. #include <windows.h>
  5. Setting the console output color
  6. BOOL Setconsolecolor (WORD wattributes)
  7. {
  8. HANDLE hconsole = GetStdHandle (Std_output_handle);
  9. if (hconsole = = Invalid_handle_value)
  10. return FALSE;
  11. return Setconsoletextattribute (Hconsole, wattributes);
  12. }
  13. const INT reader_num = 5; //number of readers
  14. Critical segments and events
  15. critical_section G_cs, G_cs_writer_count;
  16. HANDLE G_heventwriter, G_heventnoreader;
  17. int g_nreadercount;
  18. Reader thread output function (Implementation of variable parameter function)
  19. void readerprintf (char *pszformat, ...)
  20. {
  21. va_list parglist;
  22. Va_start (Parglist, Pszformat);
  23. EnterCriticalSection (&g_cs);
  24. vfprintf (stdout, Pszformat, parglist);
  25. LeaveCriticalSection (&g_cs);
  26. Va_end (parglist);
  27. }
  28. Reader thread functions
  29. unsigned int __stdcall readerthreadfun (PVOID pM)
  30. {
  31. readerprintf ("%d reader entered wait ... \ n", GetCurrentThreadID ());
  32. //Wait for the writer to complete
  33. WaitForSingleObject (G_heventwriter, INFINITE);
  34. //number of readers increased
  35. EnterCriticalSection (&g_cs_writer_count);
  36. g_nreadercount++;
  37. if (G_nreadercount = = 1)
  38. ResetEvent (G_heventnoreader);
  39. LeaveCriticalSection (&g_cs_writer_count);
  40. //Read file
  41. readerprintf ("%d reader starts reading files ... \ n", GetCurrentThreadID ());
  42. Sleep (rand ()% 100);
  43. //End reading, number of readers decreased, vacancy increased
  44. readerprintf ("%d reader ends reading file \ n", GetCurrentThreadID ());
  45. //number of readers decreased
  46. EnterCriticalSection (&g_cs_writer_count);
  47. g_nreadercount--;
  48. if (G_nreadercount = = 0)
  49. SetEvent (G_heventnoreader);
  50. LeaveCriticalSection (&g_cs_writer_count);
  51. return 0;
  52. }
  53. Writer thread output function
  54. void writerprintf (char *pszstr)
  55. {
  56. EnterCriticalSection (&g_cs);
  57. Setconsolecolor (Foreground_green);
  58. printf ("%s\n", pszstr);
  59. Setconsolecolor (foreground_red | Foreground_green | Foreground_blue);
  60. LeaveCriticalSection (&g_cs);
  61. }
  62. Writer thread functions
  63. unsigned int __stdcall writerthreadfun (PVOID pM)
  64. {
  65. writerprintf ("writer thread enters wait ...");
  66. //Waiting for the reader to read the file is zero
  67. WaitForSingleObject (G_heventnoreader, INFINITE);
  68. //Mark writer is writing file
  69. ResetEvent (G_heventwriter);
  70. //write file
  71. writerprintf ("writer begins to write files ...");
  72. Sleep (rand ()% 100);
  73. writerprintf ("writer finishes writing documents");
  74. //Mark writer end Write file
  75. SetEvent (G_heventwriter);
  76. return 0;
  77. }
  78. int main ()
  79. {
  80. printf ("reader Writer's question \ n");
  81. printf ("-by Morewindows (http://blog.csdn.net/MoreWindows)--\n\n");
  82. //Initialize events and semaphores
  83. InitializeCriticalSection (&g_cs);
  84. InitializeCriticalSection (&g_cs_writer_count);
  85. //manual position, initial trigger
  86. G_heventwriter = CreateEvent (null, True, true, null);
  87. G_heventnoreader = CreateEvent (null, FALSE, TRUE, NULL);
  88. G_nreadercount = 0;
  89. int i;
  90. HANDLE Hthread[reader_num + 1];
  91. //Start two reader threads first
  92. For (i = 1; I <= 2; i++)
  93. Hthread[i] = (HANDLE) _beginthreadex (null, 0, readerthreadfun, NULL, 0, NULL);
  94. //Start writer thread
  95. Hthread[0] = (HANDLE) _beginthreadex (null, 0, writerthreadfun, NULL, 0, NULL);
  96. Sleep (50);
  97. ///finally start other reader processes
  98. For (; I <= reader_num; i++)
  99. Hthread[i] = (HANDLE) _beginthreadex (null, 0, readerthreadfun, NULL, 0, NULL);
  100. WaitForMultipleObjects (Reader_num + 1, hthread, TRUE, INFINITE);
  101. For (i = 0; i < Reader_num + 1; i++)
  102. CloseHandle (Hthread[i]);
  103. //Destroy events and semaphores
  104. CloseHandle (G_heventwriter);
  105. CloseHandle (G_heventnoreader);
  106. DeleteCriticalSection (&g_cs);
  107. DeleteCriticalSection (&g_cs_writer_count);
  108. return 0;
  109. }

The results of the operation are as follows:

The result shows that when a reader reads a file, the writer thread goes into the wait state. When the writer thread writes a file, the reader thread waits, indicating that the reader and the writer have completed the synchronization.

This series summarizes the key segments, events, mutexes, and semaphores of thread synchronization by using the classic thread synchronization problem, and makes a summary of these four methods. Then through two well-known thread synchronization instance-producer consumer problem and reader writer problem to strengthen the understanding and application of multi-thread synchronization mutex. Hope that readers can master, so that in the written interview can be a smooth "second-kill" multi-threaded related questions, to obtain their own satisfactory offer.

From the second multi-threaded tenth producer consumer problem to the second-kill multi-threaded 11th reader writer problem can be concluded that the key to multi-threaded problem is to find all the "wait" situation and determine whether there is no need for mutually exclusive access to resources. So how do you find these better, faster and more comprehensively from the actual problem? Please see the second multi-threaded 12th Multi-threaded synchronous internal Heart--PV operation and the second multi-threading the 13th Multi-threaded synchronous internal Heart--PV operation of this two to strengthen the solution of multi-threaded synchronization problem "internal strength."

In addition, reader Writer's question can be solved with read-write lock srwlock, please see "second-order multi-threaded 14th reader Writer's question" Read and write lock Srwlock "

Reprint please indicate source, original address: http://blog.csdn.net/morewindows/article/details/7596034

Second-kill multithreading 11th reader Writer's 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.