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
- Reader and writer's question secondary read-write lock Srwlock
- #include <stdio.h>
- #include <process.h>
- #include <windows.h>
- Setting the console output color
- BOOL Setconsolecolor (WORD wattributes)
- {
- HANDLE hconsole = GetStdHandle (Std_output_handle);
- if (hconsole = = Invalid_handle_value)
- return FALSE;
- return Setconsoletextattribute (Hconsole, wattributes);
- }
- const INT reader_num = 5; //number of readers
- Critical segments and events
- Critical_section G_cs;
- SRWLOCK G_srwlock;
- Reader thread output function (Implementation of variable parameter function)
- void readerprintf (char *pszformat, ...)
- {
- va_list parglist;
- Va_start (Parglist, Pszformat);
- EnterCriticalSection (&g_cs);
- vfprintf (stdout, Pszformat, parglist);
- LeaveCriticalSection (&g_cs);
- Va_end (parglist);
- }
- Reader thread functions
- unsigned int __stdcall readerthreadfun (PVOID pM)
- {
- readerprintf ("%d reader entered wait ... \ n", GetCurrentThreadID ());
- //Reader request to read files
- Acquiresrwlockshared (&g_srwlock);
- //Read file
- readerprintf ("%d reader starts reading files ... \ n", GetCurrentThreadID ());
- Sleep (rand ()% 100);
- readerprintf ("%d reader ends reading file \ n", GetCurrentThreadID ());
- //Reader end read File
- Releasesrwlockshared (&g_srwlock);
- return 0;
- }
- Writer thread output function
- void writerprintf (char *pszstr)
- {
- EnterCriticalSection (&g_cs);
- Setconsolecolor (Foreground_green);
- printf ("%s\n", pszstr);
- Setconsolecolor (foreground_red | Foreground_green | Foreground_blue);
- LeaveCriticalSection (&g_cs);
- }
- Writer thread functions
- unsigned int __stdcall writerthreadfun (PVOID pM)
- {
- writerprintf ("writer thread enters wait ...");
- //writer apply to write file
- Acquiresrwlockexclusive (&g_srwlock);
- //write file
- writerprintf ("writer begins to write files ...");
- Sleep (rand ()% 100);
- writerprintf ("writer finishes writing documents");
- //Mark writer end Write file
- Releasesrwlockexclusive (&g_srwlock);
- return 0;
- }
- int main ()
- {
- printf ("reader writer Problem srwlock\n");
- printf ("-by Morewindows (http://blog.csdn.net/MoreWindows)--\n\n");
- //Initialize read-write lock and key segment
- InitializeCriticalSection (&g_cs);
- Initializesrwlock (&g_srwlock);
- HANDLE Hthread[reader_num + 1];
- int i;
- //Start two reader threads first
- For (i = 1; I <= 2; i++)
- Hthread[i] = (HANDLE) _beginthreadex (null, 0, readerthreadfun, NULL, 0, NULL);
- //Start writer thread
- Hthread[0] = (HANDLE) _beginthreadex (null, 0, writerthreadfun, NULL, 0, NULL);
- Sleep (50);
- ///finally start other reader processes
- For (; I <= reader_num; i++)
- Hthread[i] = (HANDLE) _beginthreadex (null, 0, readerthreadfun, NULL, 0, NULL);
- WaitForMultipleObjects (Reader_num + 1, hthread, TRUE, INFINITE);
- For (i = 0; i < Reader_num + 1; i++)
- CloseHandle (Hthread[i]);
- //Destroy critical segment
- DeleteCriticalSection (&g_cs);
- return 0;
- }
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