C + + Supplements--c++ Multithreading Introduction
Preface
The C + + library file also provides support for multithreading, which mainly includes the header file thread to use multithreading in C + +. Some of its multithreading-related methods differ from the C language. We need to discuss how to use multithreading under C + + programming.
Body1. Example
As with the C-language multithreading introduction, let's look at a C + + multi-threading example first.
multi-threaded header files in #include <iostream> #include <thread>//c++ # include <windows.h>using namespace std; void run (const void *p) {const char *mess = (const char*) p;printf ("Thread id =%ld\n", GetCurrentThreadID ()); MessageBoxA (NULL, Mess, "thread", 0);} int main () {printf ("******c++ Multithreading introduces ***by david***\n");//create four threads thread T1 (run, "I"), Thread T2 (Run, "Love"), thread t3 (run, "You"); thread t4 (Run, "BABY");//block main thread t1.join (); T2.join (); T3.join (); T4.join (); return 0;}
Run
Open up space on the stack to create four threads and pop up four windows in parallel. From left to right is the order in which the window pops up, and from the result, they are concurrent and asynchronous.
2. Summary
Creating multithreading in C + + is simple, using the thread class provided by the standard library. When you create a thread instance, you specify the thread function and the function arguments.
function join ()
Function: Blocks the calling thread until the thread finishes, before the calling thread can continue execution.
For example, T1.join () will block the main thread until the thread T1 execution ends, and the main thread will then execute down.
Later, we will introduce the other methods in C + + multithreading, as well as the child-thread mutex and the master thread conflict.
Directory of this column
- C + + Supplements directory
Directory of all content
C + + Supplements--c++ Multithreading Introduction