Second kill multithreading 11th---readers write questions __ multithreading

Source: Internet
Author: User
Tags mutex rand

Like the producer consumer Problem of the tenth producer consumer problem, the reader writer is also a very famous synchronization problem . The reader writes the question description very simple, has a writer many readers, several readers may simultaneously read the file, but the writer does not allow the reader to read the document when writes the document, also has the reader to read the document the writer also does not have to be able to write the document.

The above is the reader writer problem diagram, similar to the producer consumer problem analysis process, first of all to find out which belongs to the "waiting" situation.

first. The writer has to wait until there is no reader to write the document.

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

After you find the "wait" situation, see if there are any resources that you want to mutually exclusive access. Because there is only one writer and readers are read files that can be shared, there is no resource that requires mutually exclusive access by topic. Similar to the beautiful color output in the previous article, we made a color setting for the producer output code (see the "VC Console color Setting" in the console output color setting). Therefore, it is possible to add a mutex access here, or it is very likely that the reader thread will have output before the writer thread restores the console color settings. Therefore, the output statement to be mutually exclusive access processing, the revised reader and the writer's output function is as follows:

Reader thread output 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);
}
The 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);
}

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

resolves the mutex output problem, then consider how to implement synchronization issues . you can set a variable to record the number of readers who are reading the file, and the first reader to start reading the file is responsible for closing the sign that allows the writer to enter, and the last reader to read the document is responsible for opening the sign that allows the writer to enter ... . The first kind of "wait" situation is solved. The second "Wait" scenario is when a writer enters, so the reader is unable to enter, and an event is used to complete the task-all readers are waiting for this event and the writer is responsible for triggering the event and setting the event to not be triggered .... . See the comments in the code for details:

Reader and writer questions #include <stdio.h> #include <process.h> #include <windows.h>//Set 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//key segments and Events critical_section G_cs, G_cs_writer_count;
HANDLE G_heventwriter, G_heventnoreader;
int g_nreadercount;
Reader thread output function (realization 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 function unsigned int __stdcall readerthreadfun (pvoid PM) {readerprintf ("number%d reader enters wait ... \ n", GetCurrentThread
    Id ());

    Waiting for the writer to complete WaitForSingleObject (G_heventwriter, INFINITE);
    The number of readers increased entercriticalsection (&g_cs_writer_count); G_nreadercount++;
    if (G_nreadercount = = 1) resetevent (G_heventnoreader);

    LeaveCriticalSection (&g_cs_writer_count);

    Read file readerprintf ("Number%d reader begins reading file ... \ n", GetCurrentThreadID ());

    Sleep (rand ()% 100);

    End reading, the number of readers is reduced, the vacancy is increased readerprintf ("Readers with number%d end read files \ n", GetCurrentThreadID ());
    The number of readers reduced entercriticalsection (&g_cs_writer_count);
    g_nreadercount--;
    if (G_nreadercount = = 0) setevent (g_heventnoreader);

    LeaveCriticalSection (&g_cs_writer_count);
return 0;
    //writer thread output function void writerprintf (char *pszstr) {entercriticalsection (&AMP;G_CS);
    Setconsolecolor (Foreground_green);
    printf ("%s\n", pszstr); Setconsolecolor (foreground_red | Foreground_green |
    Foreground_blue);
LeaveCriticalSection (&g_cs);
    //writer thread function unsigned int __stdcall writerthreadfun (pvoid PM) {writerprintf ("writer thread enters wait ...");
    Readers waiting to read the document are zero WaitForSingleObject (G_heventnoreader, INFINITE); Tag writer is writing file resetevent (g_heventWriter);
    Write File writerprintf ("The writer begins to write the file ...");
    Sleep (rand ()% 100);

    Writerprintf ("writer ends writing file");
    Mark writer ends Writing file setevent (g_heventwriter);
return 0;
    int main () {printf ("Reader problem \ n");

    printf ("-by Morewindows (http://blog.csdn.net/MoreWindows)--\n\n");
    Initialization event and Semaphore InitializeCriticalSection (&AMP;G_CS);

    InitializeCriticalSection (&g_cs_writer_count);
    Manual placement, initially triggered g_heventwriter = CreateEvent (null, True, true, null);
    G_heventnoreader = CreateEvent (null, FALSE, TRUE, NULL);

    G_nreadercount = 0;
    int i;
    HANDLE Hthread[reader_num + 1];  Start two reader threads for (i = 1; I <= 2; i++) hthread[i] = (HANDLE) _beginthreadex (null, 0, readerthreadfun, NULL, 0,
    NULL);
    Starter writer thread hthread[0] = (HANDLE) _beginthreadex (null, 0, writerthreadfun, NULL, 0, NULL);
    Sleep (50); Finally, start other reader's End for (; I <= reader_num; i++) hthread[i] = (HANDLE) _beginthreadex (NULL, 0, Readerthreadfun, NU
 LL, 0, NULL);   WaitForMultipleObjects (Reader_num + 1, hthread, TRUE, INFINITE);

    for (i = 0; i < Reader_num + 1; i++) CloseHandle (hthread[i));
    Destruction of events and semaphores CloseHandle (g_heventwriter);
    CloseHandle (G_heventnoreader);
    DeleteCriticalSection (&g_cs);
    DeleteCriticalSection (&g_cs_writer_count);
return 0; }

Results:

It can be seen from the results that when a reader reads a file, the writer thread enters the waiting state. When a writer thread writes a file, the reader thread waits in line, indicating that the reader and the writer have completed the synchronization.

This series enumerates the key segments, events, mutexes and semaphores of thread synchronization through the classic thread synchronization problem, and makes a summary of these four methods. Then, through two famous thread synchronization instances-producer consumer problem and reader writer problem, the understanding and application of multithreading synchronization mutex are enhanced. I hope that readers will be able to master, so in the written interview can be smooth "second kill" multithreading related questions, to obtain their satisfaction with the offer.

From "Second to kill multithreading tenth" producer consumer problem "to" Seconds to kill multithreading 11th reader problem "can be found that the key to multithreading problem is to find all the" waiting "situation and to determine whether there is a need for mutually exclusive access resources. So how do you find this out better, faster and more comprehensively from the actual problem? Please see "Second to kill multithreading 12th multithread synchronous internal strength--PV operation" and "second to kill multithreading 13th multithread synchronization internal Skills--PV operation" These two to enhance the solution of multithreading synchronization problem "internal strength."

In addition, readers write the problem can be used to read and write lock srwlock to solve, please see "Seconds to kill multithreading 14th readers write the question of reading and writing lock Srwlock"

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

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.