C ++ multi-thread programming 1 [about data competition]

Source: Internet
Author: User

 

Users are familiar with the advantages of multithreading, and can make full use of system resources to achieve the maximum value through reasonable scheduling.ProgramBut if it is not properly designed, it will be contrary to the original intention and bring more trouble. This article mainly summarizes and summarizes the "data competition" issue in multi-thread programming, some functions under Win32 are described.

Data competition is a key technique in multi-threaded programming. There are four common solutions: critical section, mutex, event, and semaphore.

The critical section is generally not recommended. The following three types are introduced.

1. mutex

Friends who have learned about computer networks believe that they should be familiar with the licensing ring network. The mutex serves as a token, and each host must compete to apply for this token, the "obtained" host has the permission to send packets online, while the "token" only has one, the "token" can only be "applied for" by other hosts after the current user is "released ".

There is only one mutex. Each thread is used for competition. After a thread is obtained, other threads have to wait before it is released.

1. On the Win32 platform, the mutex is a handle. The initialization method is as follows:

Handle hmutex;

Hmutex = createmutex (null, true, null); // after creation, the current thread initially occupies the mutex.

Releasemutex (hmutex); // after being created, the mutex is released in the main thread so that the subthread can apply for use.

Hmutex = openmutex (mutant_all_access, true, null); // open the mutex and declare that the sub-thread can inherit the mutex handle.

2. Application and release

Waitforsingleobject (hmutex, DWORD dwtimeout );

/* Do the task ;*/

Releasemutex (hmutex );

For example, you can set the timeout to 100 milliseconds, as shown below:

If (wait_timeout = waitforsingleobject (hrecveven, 100 )){
/* Do something ;*/}
Else {

/* Do the task ;*/

Releasemutex (hmutex );}

Ii. Event

The event is often used as a "traffic light". You can easily set the light to "red" in the thread to block some threads requesting the resource, or set it to "green ", start all threads blocked by this part of resources.

The most common scenario is the network buffer. When the data processing thread extracts data packets from the network buffer for processing, the first operation is to determine whether the buffer is empty, if it is not empty, it is extracted and processed. If it is empty, it is cyclically detected. This will greatly waste CPU resources in cyclic detection. The best way is to use mutex events, every time waitforsingleobject is used to apply for resources, if it is "red", the thread is blocked, and the write buffer thread executes the setevent function when writing data, in this way, the "green" light is broadcast throughout the process space, so that the processing thread status can be changed from blocking to ready to execute operations.

A common mistake made when using mutex is to mistakenly regard the event as mutex to prevent data competition in two threads, as shown in the following example:

Handle hevent;

Hevent = createevent (null, true, false, null); // real-start semaphore, initial status non-signal notification

Setevent (hevent); // signal notification

Threada

{

Waitforsingleobject (hevent );

Resetevent (hevent );

/* Do the task ;*/

Setevent (hevnet );

}

Threadb

{

Waitforsingleobject (hevent );

Resetevent (hevent );

/* Do the task ;*/

Setevent (hevnet );

}

In the above example, what would happen unexpectedly? When thread a executes the mutex event and sets the light to "red", thread B can still apply for and execute the mutex event, this is because, after a waitforsingleobject succeeds, B may have seized the CPU and executed waitforsingleobject before a executes the resetevent, So B has the right to execute the resetevent, in this way, both A and B have the right to execute. In this case, two people can control the "traffic lights", resulting in "traffic chaos ", the best way is that only one thread in all threads can turn on and off the lights, or implement mutex protection for mutex events to prevent data competition.

Ii. semaphores semaphore

The significance of semaphores can be understood as the number of resources, for example, the number of seats in the queuing system. All the values of semaphores are greater than or equal to 1, when the value is equal to 1, the semaphore degrades to mutex.

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.