Multithreading one of the top ten classic cases dual-thread read and write queue data

Source: Internet
Author: User
Tags mutex semaphore

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

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

Welcome to follow Weibo: Http://weibo.com/MoreWindows

In the "second multi-threaded series" in the first 15 articles introduced the concept of multi-threaded, multi-threaded synchronization mutual exclusion problem "seconds to kill multithreading," the fourth one classic multi-threaded synchronization problem and solve multi-threaded synchronous mutual exclusion of common methods-key segments, events, mutual exclusion, signal volume, read and write locks. 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 of all, the first article--"Seconds to kill multithreading," the 16th one of the top ten classic cases of double-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.

This case is from http://bbs.csdn.NET/topics/390383114, thank hehening88 for providing the topic, hereby acknowledge.

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 the second multi-threaded 11th reader Writer's question and the second-kill multithreading 14th reader Writer's question Srwlock), but in fact, if the queue as a buffer, this case is obviously a producer of consumer problems (see the Seconds to kill multithreading the tenth producer consumer problem). 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.

After the analysis, consider what data structure to use, also in accordance with the "second-order multi-threaded tenth producer consumer problem" in the practice. 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 second kill multithreading eighth classic thread synchronization semaphore semaphore, the code of the Setconsolecolor is used to change the text color of the console, in particular, you can refer to the VC console color settings.

One of the top ten classic cases of multithreading double-threaded read-write queue data complete code: [CPP]View PlainCopy
  1. Seconds to kill multithreading the 16th one of the ten classic cases of multithreading double-threaded read and 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; //note here ndata++; the difference between ++ndata causes the last number to be read .
  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 ("second-kill multithreading, the 16th multithreading Ten classic cases of double-threaded 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

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

Welcome to follow Weibo: Http://weibo.com/MoreWindows

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.