Turn---seconds to kill multithreading 14th reader Writer's question following read/write lock Srwlock

Source: Internet
Author: User
Tags function prototype

We use events and a variable that records the number of readers to solve reader-writer problems in the second-to-last multi-threaded 11th article Reader-writer question. The problem has been solved, but the code is a bit complicated. This article will introduce a new method-read-write lock srwlock to solve this problem. read-write locks also distinguish between the thread that wants to read the resource value (the reader thread) and the thread that wants to update the resource (the writer thread) while protecting the resource. For reader threads, read-write locks allow them to execute concurrently. When a writer thread occupies a resource, the read-write lock causes the other writer thread and reader thread to wait. So using a read-write lock to solve reader-writer problems can make the code very clear and concise.

Here's a look at how to use read and write locks, note that compiling a read-write lock program requires VS2008, and running a read-write lock program on a Vista or Windows Server2008 system (more than these two more advanced systems can). The main function of the read-write lock is five, which is divided into initialization function, writer thread request and release function, reader thread request and release function, the following is the detailed function instruction:

The first of the initializesrwlock

function function: Initialize read-write lock

Function prototype:VOID initializesrwlock(psrwlock SRWLock);

Function Description: Initialize (without deleting or destroying Srwlock functions, the system will automatically clean up)

A second acquiresrwlockexclusive

function function: Writer thread request write resource.

Function prototype:VOID acquiresrwlockexclusive(psrwlock SRWLock);

A third releasesrwlockexclusive

function function: The writer thread writes the resource complete and frees up the resource usage.

Function prototype:VOID releasesrwlockexclusive(psrwlock SRWLock);

Fourth one acquiresrwlockshared

function function: Reader thread request read resource.

Function prototype:VOID acquiresrwlockshared(psrwlock SRWLock);

Fifth one releasesrwlockshared

function function: The reader thread ends reading the resource and frees up the resource.

Function prototype:VOID releasesrwlockshared(psrwlock SRWLock);

Note A thread can only lock resources once and cannot lock resources multiple times.

Use the read-write lock to refine the code as follows (the implementation of the variable parameter function in the code is described in "using variable parameters in c,c++", console color settings See "VC Console Color Settings"):

[CPP]View Plaincopy
  1. Reader and writer's question secondary read-write lock Srwlock
  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;
  16. SRWLOCK G_srwlock;
  17. Reader thread output function (Implementation of variable parameter function)
  18. void readerprintf (char *pszformat, ...)
  19. {
  20. va_list parglist;
  21. Va_start (Parglist, Pszformat);
  22. EnterCriticalSection (&g_cs);
  23. vfprintf (stdout, Pszformat, parglist);
  24. LeaveCriticalSection (&g_cs);
  25. Va_end (parglist);
  26. }
  27. Reader thread functions
  28. unsigned int __stdcall readerthreadfun (PVOID pM)
  29. {
  30. readerprintf ("%d reader entered wait ... \ n", GetCurrentThreadID ());
  31. //Reader request to read files
  32. Acquiresrwlockshared (&g_srwlock);
  33. //Read file
  34. readerprintf ("%d reader starts reading files ... \ n", GetCurrentThreadID ());
  35. Sleep (rand ()% 100);
  36. readerprintf ("%d reader ends reading file \ n", GetCurrentThreadID ());
  37. //Reader end read File
  38. Releasesrwlockshared (&g_srwlock);
  39. return 0;
  40. }
  41. Writer thread output function
  42. void writerprintf (char *pszstr)
  43. {
  44. EnterCriticalSection (&g_cs);
  45. Setconsolecolor (Foreground_green);
  46. printf ("%s\n", pszstr);
  47. Setconsolecolor (foreground_red | Foreground_green | Foreground_blue);
  48. LeaveCriticalSection (&g_cs);
  49. }
  50. Writer thread functions
  51. unsigned int __stdcall writerthreadfun (PVOID pM)
  52. {
  53. writerprintf ("writer thread enters wait ...");
  54. //writer apply to write file
  55. Acquiresrwlockexclusive (&g_srwlock);
  56. //write file
  57. writerprintf ("writer begins to write files ...");
  58. Sleep (rand ()% 100);
  59. writerprintf ("writer finishes writing documents");
  60. //Mark writer end Write file
  61. Releasesrwlockexclusive (&g_srwlock);
  62. return 0;
  63. }
  64. int main ()
  65. {
  66. printf ("reader writer Problem srwlock\n");
  67. printf ("-by Morewindows (http://blog.csdn.net/MoreWindows)--\n\n");
  68. //Initialize read-write lock and key segment
  69. InitializeCriticalSection (&g_cs);
  70. Initializesrwlock (&g_srwlock);
  71. HANDLE Hthread[reader_num + 1];
  72. int i;
  73. //Start two reader threads first
  74. For (i = 1; I <= 2; i++)
  75. Hthread[i] = (HANDLE) _beginthreadex (null, 0, readerthreadfun, NULL, 0, NULL);
  76. //Start writer thread
  77. Hthread[0] = (HANDLE) _beginthreadex (null, 0, writerthreadfun, NULL, 0, NULL);
  78. Sleep (50);
  79. ///finally start other reader processes
  80. For (; I <= reader_num; i++)
  81. Hthread[i] = (HANDLE) _beginthreadex (null, 0, readerthreadfun, NULL, 0, NULL);
  82. WaitForMultipleObjects (Reader_num + 1, hthread, TRUE, INFINITE);
  83. For (i = 0; i < Reader_num + 1; i++)
  84. CloseHandle (Hthread[i]);
  85. //Destroy critical segment
  86. DeleteCriticalSection (&g_cs);
  87. return 0;
  88. }

In contrast to the " second-kill multithreaded 11th reader writer Problem " in the code can be found that the code is indeed a lot more refreshing. This program can be compiled with VS2008, but running under the XP system will result in an error.

In the Win7 system can be run correctly, the result:

Finally summarize the read-write lock SRWLock

1. Read-write locks are initialized after they are declared, but not destroyed, and the system automatically cleans up read and write locks.

2. The reader and writer call different application functions and release functions, respectively.

Turn---seconds to kill multithreading 14th reader Writer's question following read/write lock Srwlock

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.