C + + Supplements-Multithreading: Atomic operations Resolve thread conflicts

Source: Internet
Author: User

C + + Supplements-Multithreading: Atomic operations Resolve thread conflicts

Preface

Manipulating global variables in multi-threading generally causes thread conflicts, and in order to resolve thread conflicts, atomic operations are introduced.

Body1. Thread Conflicts

#include <stdio.h> #include <stdlib.h> #include <process.h> #include <windows.h>int g_count = 0; void count (void *p) {Sleep (+);    Do some work//each thread to add g_count 1 total 10 times for (int i = 0; i <; i++) {g_count++;} Sleep (+);   Do some work}int main (void) {printf ("****** multithreaded access global variable demo ***by david***\n");//create 10 threads handle Handles[10];for (int i = 0; i < 10; i++) {for (int j = 0; J <; J + +) {Handles[j] = _beginthread (count, 0, NULL);} WaitForMultipleObjects (handles, 1, INFINITE);p rintf ("%d time G_count =%d\n", I, g_count);//Reset G_count = 0;} GetChar (); return 0;}
Run


Theoretically, the final result of G_count should be 100, but the fact is not, not only the result is not necessarily 100, and each time the results are likely to be different. The reason is that when multiple threads are accessing the same global variable, especially when the modification is in progress, it can cause a conflict. Detailed Explanation:

Set breakpoints to view disassembly


g_count++ is divided into three steps:

1. Move the contents of the G_count from memory to register EAX

2. Add the Register EAX 1

3. Move the contents of the register EAX to the address of the memory G_count

After three steps, the value of the G_count is successfully added 1.

The CPU executes a time slice that contains multiple instructions, and the execution of each instruction is not interrupted, but if an operation contains more than one instruction, it is likely that the operation will be interrupted. g_count++; This is the operation.

G_count was successfully added to the 100 premise: each plus 1, is based on the last plus 1 successful completion of the basis. That is, if the last plus 1 is interrupted, this time the addition of 1 will not be the last plus 1 cumulative effect. Naturally, the final result is likely to be less than 100.


2. Atomic Operation

atomic operations are actions that are not interrupted by the thread-scheduling mechanism, which, once started, has to be executed until the end of the operation. An atomic operation can be a step or multiple steps, but its order cannot be disrupted, or it can be cut off only the execution part. Atomic operations are generally implemented by the underlying assembly.

A number of atomic manipulation functions are provided in the header file WinNT.h, which use self-locking to guarantee the atomicity of the operation, such as the self-increment operation

InterlockedIncrement,

Function prototypes

LONG cdecl_non_wvmpure InterlockedIncrement (
_inout_ _interlocked_operand_ LONG volatile *addend
);

For other related actions, please check the header file yourself.

Using this function, we modify the thread function count. The modification is simple, just change the g_count++ to InterlockedIncrement ((LONG) &g_count);

Run as follows


Obviously, under atomic manipulation, we can certainly get the right result.




Directory of this column

    • C + + Supplements directory
Directory of all content
    • CCPP Blog Directory



C + + Supplements-Multithreading: Atomic operations Resolve thread conflicts

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.