Multi-threaded Face Question series (16): Multithreading one of the top ten classic cases dual-thread read-write queue data

Source: Internet
Author: User
Tags mutex semaphore

The first 15 introduces the related concepts of multithreading, multi-threaded synchronization mutual Exclusion (fourth) and the common methods of solving multi-threaded synchronous mutual exclusion--key segment, event, mutex, semaphore, read-write lock. In order to make people more proficient in the use of multi-threading, there will be 10 articles to explain 10 multi-threaded use cases, I believe after reading these 10 will allow you to more comfortable use of multithreading.

First, the first--the 16th one of the top ten classic cases of multithreading dual-thread read-write queue data

One of the top ten classic cases of multithreading double-threaded read-write queue data case Description:

The response function for a button in the MFC dialog box implements two functions:
The display data simultaneously processes the data, therefore opens two threads, one thread displays the data (opens a timer, responds to the WM_TIMER message to add the data to the Teechart chart at a certain time interval and displays) simultaneously adds the data in the queue troop tail, another thread from the team queues the head to go to the data to process.

Here's how to solve this case. Let's start with the analysis.

One of the top ten classic cases of multithreading double-threaded read-write queue data case study:

This is a case where a thread reads data to the queue header in the queue, and a thread writes data to the queue's end. It looks much like the reader's question (see 11 and 14), but in fact, if the queue is considered a buffer, this case is obviously a producer consumer problem (see tenth). So we follow the idea of producer consumers to analyze the case of "wait" in detail:

1. When the queue is empty, the read data thread must wait for the write data to write to the queue. This means that when the queue is empty, the read data thread waits for the data in the queue .

2. When the queue is full, the write data thread must wait for the read data thread to read the data to the queue. that is, when the queue is full, write to the data thread to wait for the queue to have empty space.

Do I need to be mutually exclusive when accessing the queue? this will depend on the data structure implementation of the queue, if vectors in the STL are used, because the vectors will grow dynamically. Therefore, to do mutex protection. If a loop queue is used, the read data thread has a read pointer, the write data thread has a write pointer, each accesses data at a different location in the queue, so there is no mutex protection.

Once the analysis is complete, consider what data structure to use, and follow the same approach in the tenth article. Use two semaphores, one to record the number of slots in the loop queue, one to record the number of products in the loop queue (not the number of seats). The code is very easy to write, and the complete source code is given below.

The semaphore correlation function in the code can refer to the eighth chapter, the Setconsolecolor in the code is used to change the text color of the console, in particular, the VC console color settings can be consulted.

One of the top ten classic cases of multithreading double-threaded read-write queue data complete code: [CPP]View PlainCopy
  1. 16th one of multithreading ten classic cases dual-thread read-write queue data
  2. http://blog.csdn.net/MoreWindows/article/details/8646902
  3. #include <stdio.h>
  4. #include <process.h>
  5. #include <windows.h>
  6. #include <time.h>
  7. const INT queue_len = 5;
  8. int G_arrdataqueue[queue_len];
  9. int g_i, G_j, G_ndatanum;
  10. Key sections are used to ensure mutually exclusive output on the screen
  11. Critical_section G_cs;
  12. The semaphore G_hempty indicates that the vacancy g_hfull in the queue indicates a non-vacancy in the queue
  13. HANDLE G_hempty, G_hfull;
  14. Setting the console output color
  15. BOOL Setconsolecolor (WORD wattributes)
  16. {
  17. HANDLE hconsole = GetStdHandle (Std_output_handle);
  18. if (hconsole = = Invalid_handle_value)
  19. return FALSE;
  20. return Setconsoletextattribute (Hconsole, wattributes);
  21. }
  22. Read Data thread functions
  23. unsigned int __stdcall readerthreadfun (PVOID pM)
  24. {
  25. int ndata = 0;
  26. While (Ndata <)
  27. {
  28. WaitForSingleObject (G_hfull, INFINITE);
  29. Ndata = G_arrdataqueue[g_i];
  30. G_i = (g_i + 1)% Queue_len;
  31. EnterCriticalSection (&g_cs);
  32. printf ("read data from the queue%d\n", ndata);
  33. LeaveCriticalSection (&g_cs);
  34. Sleep (rand ()% 300);
  35. ReleaseSemaphore (G_hempty, 1, NULL);
  36. }
  37. return 0;
  38. }
  39. Write Data thread functions
  40. unsigned int __stdcall writerthreadfun (PVOID pM)
  41. {
  42. int ndata = 0;
  43. While (Ndata <)
  44. {
  45. WaitForSingleObject (G_hempty, INFINITE);
  46. G_arrdataqueue[g_j] = ++ndata;
  47. G_j = (g_j + 1)% Queue_len;
  48. EnterCriticalSection (&g_cs);
  49. Setconsolecolor (Foreground_green);
  50. printf ("Write data%d to queue \ n", ndata);
  51. Setconsolecolor (foreground_red | Foreground_green | Foreground_blue);
  52. LeaveCriticalSection (&g_cs);
  53. Sleep (rand ()% 300);
  54. ReleaseSemaphore (G_hfull, 1, NULL);
  55. }
  56. return 0;
  57. }
  58. int main ()
  59. {
  60. printf ("16th multithreading ten classic cases double thread read and write queue data \ n");
  61. printf ("-by Morewindows (http://blog.csdn.net/MoreWindows/article/details/8646902)-\n\n");
  62. InitializeCriticalSection (&g_cs);
  63. G_hempty = CreateSemaphore (null, Queue_len, queue_len, NULL);
  64. G_hfull = CreateSemaphore (null, 0, queue_len, NULL);
  65. Srand (Time (NULL));
  66. g_i = G_j = 0;
  67. HANDLE hthread[2];
  68. Hthread[0] = (HANDLE) _beginthreadex (null, 0, readerthreadfun, NULL, 0, NULL);
  69. HTHREAD[1] = (HANDLE) _beginthreadex (null, 0, writerthreadfun, NULL, 0, NULL);
  70. WaitForMultipleObjects (2, Hthread, TRUE, INFINITE);
  71. For (int i = 0; i < 2; i++)
  72. CloseHandle (Hthread[i]);
  73. CloseHandle (G_hempty);
  74. CloseHandle (G_hfull);
  75. DeleteCriticalSection (&g_cs);
  76. return 0;
  77. }

One of the top ten classic cases of multithreading dual-thread read-write queue data run Result:

The results of the program run as follows:

This package is: http://download.csdn.net/detail/morewindows/5136035

Multi-threaded Face Question series (16): Multithreading one of the top ten classic cases dual-thread read and write queue data

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.