Second kill multi-thread 16th multiple threads one of the top ten typical cases of dual-thread read/write queue data

Source: Internet
Author: User

This article supporting procedures: http://download.csdn.net/detail/morewindows/5136035

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

Welcome to Weibo: http://weibo.com/MoreWindows

 

Introduced the concept of multithreading in the first 15 articles of the second kill multi-thread series, multi-thread synchronization mutex problem: Second kill multithreading Article 4 typical multi-thread synchronization problem and common methods to solve multi-thread synchronization mutex-key segments, events, mutex volumes, semaphores, and read/write locks. To allow you to use multithreading more skillfully, we will have ten articles to explain ten multi-threaded use cases. I believe that after reading these ten articles, you will be able to use multithreading more easily.

First, let's take a look at the first article-"second kill multi-thread 16th multi-threaded Top Ten typical cases"

Description of the case of one of the top ten typical cases of multi-thread reading/writing queue data:

The response function of a button in the MFC dialog box implements two functions:
The display data is processed at the same time, so two threads and one thread are enabled to display the data (with a timer enabled, the response wm_timer message is added and displayed to the teechart chart at a certain interval) at the same time, add data at the end of the queue, and the other thread processes the data from the queue header.

This case is from http://bbs.csdn.net/topics/390383114. Thank you for your question in hehening88.pdf.

Next we will solve this case. First, let's analyze it.

 

Case study of one of the top ten typical cases of multi-thread reading/writing queue data:

In this case, a thread reads data from the queue header, and a thread writes data to the end of the queue. It looks like a reader writer problem (see Second kill multi-thread 11th reader writer problem and second kill multi-thread 14th reader writer problem following read/write lock srwlock, if the queue is regarded as a buffer, this case is obviously a producer consumer problem (see Second kill multi-thread Article 10 producer consumer problem). Therefore, we analyze the "Waiting" Situation in the case based on the ideas of producers and consumers:

1. When the queue is empty, the read data thread must wait for the data to be written to the queue. That is to sayWhen the queue is empty, the read data thread needs to wait for data in the queue.

2. When the queue is full, the Data Writing thread must wait for the Data Reading thread to read data from the queue. That is to sayWhen the queue is full, the Data Writing thread needs to wait for the queue to have a blank space..

Do I need mutual exclusion when I access the queue?This depends on the data structure of the queue.If you use the vector in STL, the vector will grow dynamically. Therefore, mutex protection is required. If a circular queue is used, the read data thread has a read pointer, And the write data thread has a write pointer. Each thread will access data in different locations in the queue, so mutual exclusion protection is not required.

After the analysis is complete, consider what data structure to use, also in accordance with the practice in second kill multi-thread Article 10 producer and consumer issues. Two semaphores are used. One is used to record the number of hollow bits in the cyclic queue, and the other is used to record the number of products in the cyclic queue (the number of non-vacant bits ). The code is very easy to write. The complete source code is provided below.

For semaphores related functions in the code, refer to second kill multithreading Article 8 typical thread synchronization semaphores semaphore. The setconsolecolor in the code is used to change the text color of the console. For details, refer to VC console color settings.

 

Full code of "multi-thread reading/writing queue data in one of the top ten typical cases of multithreading:
// Second kill multithreading 16th multi-threaded Top Ten classic cases one of the double thread read/write queue data // http://blog.csdn.net/MoreWindows/article/details/8646902#include <stdio. h> # include <process. h> # include <windows. h> # include <time. h> const int queue_len = 5; int g_arrdataqueue [queue_len]; int g_ I, g_j, g_ndatanum; // key segment is used to ensure mutex output of critical_section g_cs on the screen; // semaphores g_hempty indicates that g_hfull indicates that handle g_hempty and g_hfull are not empty in the queue; // you can specify the color bool setconsolecolor (word wattributes) {handle hconsole = getstdhandle (std_output_handle ); if (hconsole = invalid_handle_value) return false; return setconsoletextattribute (hconsole, wattributes);} // read data thread function unsigned int _ stdcall readerthreadfun (pvoid pm) {int ndata = 0; while (ndata <20) {waitforsingleobject (g_hfull, infinite); ndata = g_arrdataqueue [g_ I]; g_ I = (g_ I + 1) % queue_len; entercriticalsection (& g_cs); printf ("read data from the queue % d \ n", ndata); leavecriticalsection (& g_cs); sleep (RAND () % 300 ); releasesemaphore (g_hempty, 1, null);} return 0;} // write data thread function unsigned int _ stdcall writerthreadfun (pvoid pm) {int ndata = 0; while (ndata <20) {waitforsingleobject (g_hempty, infinite); g_arrdataqueue [g_j] = ++ ndata; g_j = (g_j + 1) % queue_len; entercriticalsection (& g_cs ); setconsolecolor (foreground_green); printf ("Write Data % d to queue \ n", ndata); setconsolecolor (foreground_red | foreground_green | foreground_blue); then (& g_cs ); sleep (RAND () % 300); releasesemaphore (g_hfull, 1, null);} return 0;} int main () {printf ("second kill multithreading 16th articles multithreading Top Ten classic cases dual-thread read/write queue data \ n"); printf ("-by morewindows (http://blog.csdn.net/MoreWindows/article/details/8646902)-\ n "); values (& g_cs); g_hempty = createsemaphore (null, queue_len, queue_len, null); g_hfull = createsemaphore (null, 0, queue_len, null); srand (Time (null )); g_ I = g_j = 0; handle hthread [2]; hthread [0] = (handle) _ beginthreadex (null, 0, readerthreadfun, null, 0, null ); hthread [1] = (handle) _ beginthreadex (null, 0, writerthreadfun, null, 0, null); waitformultipleobjects (2, hthread, true, infinite ); for (INT I = 0; I <2; I ++) closehandle (hthread [I]); closehandle (g_hempty); closehandle (g_hfull); deletecriticalsection (& g_cs ); return 0 ;}

 


Results of "Reading and Writing queue data in two threads" in one of the top ten typical cases of multithreading:

The program running result is as follows:

This article supporting procedures: http://download.csdn.net/detail/morewindows/5136035

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

Welcome to Weibo: http://weibo.com/MoreWindows

 

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.