C + + Supplements-Multithreading: The main thread synchronizes with child threads
Preface
In multithreaded programming, it is sometimes necessary to require the main thread to synchronize with the child thread.
BodyProgram Demo
The following example illustrates the synchronization problem between the main thread and the child thread.
Program Description:
In the main thread, there is an integer variable count, initialized to 0. The main thread passes the address of count to the open child thread, the child thread prints the obtained value, then the main thread increments the value of count, opens another child thread again, passes the address of count ...
#include <stdio.h> #include <stdlib.h> #include <process.h> #include <Windows.h> #define Thread _num 20void thread_go (void *p) {Sleep (+); Do some workint i = * (int*) p; Sleep (+); Do some workprintf ("thread%d, Count%d\n", GetCurrentThreadID (), i);} int main (void) {printf ("****** main thread and child thread synchronization problem demo ***by david***\n"); HANDLE handles[thread_num];int count = 0;for (int i = 0; i < Thread_num; i++) {Handles[i] = _beginthread (thread_go, 0, & Amp;count); Sleep (+); Do some workwaitforsingleobject (Handles[i], INFINITE); Open this line of code can also realize the main thread and sub-thread synchronization count++; Before the child thread gets this value, the main thread is likely to modify it so that a count is skipped. }//permanently waits for all child threads to end WaitForMultipleObjects (Thread_num, handles, TRUE, INFINITE); GetChar (); return 0;}
Run
The result of this operation is specially selected, because it exposes all the problems:
- The results of the theoretical report are from 0 to 19. Some of the running results are skipped, such as 1,15.
- Some numbers are repeated, such as 14,16.
- Why does 20 appear? This is not supposed to be.
Problem Analysisfor a detailed analysis of these three issues, the reasons for this are:Question one
Some of them are skipped. This is in the code of the count++, this sentence after a detailed explanation. Look at the code comment to understand.
question two
Some numbers are repeated. This is also the same reason as the previous problem: Before the last thread gets the count value, the value of count is changed by the main thread, so when the previous thread gets the value of count, it is very likely that the value it gets is the same value as the next child thread gets. So I repeated it.
question three
Many reasons, one can be: the last I and count of the size is 20, the loop should end, the main thread is interrupted. If a strand Chengjo has not saved the value of count, the child thread holds the last value of Count 20.
Subsequent articles, through the corresponding methods, to achieve the master thread synchronization.
Directory of this column
- C + + Supplements directory
Directory of all content
C + + Supplements-Multithreading: The main thread synchronizes with child threads