C++11 Multi-line Cheng experience

Source: Internet
Author: User

Before the C++11 standard, using C + + to write multithreaded programs either requires a third-party API, such as Pthread, or relies on APIs provided by the running platform, which is inconvenient to use. and C++11 provides platform-independent language-level support, which greatly facilitates our developers.

Multithreading support for c++11 is primarily done by using classes or functions in the header file as follows: <atomic><thread><mutex><condition_variable><future >.

New Thread

Creates a new thread through the Std::thread class. There are generally two ways:
1) Pass a function (can be a function pointer or lambda expression, etc.)
2) passes an object that overloads the operator (), or that the object must have a function named operator ().

Here's a look at the example (Visual Studio 2015 runs through):

#include <thread>#include <iostream>using namespace STD;//A normal functionvoidFunintNUM) {cout<<"The function child thread begin...\n";cout<<"I come from Function fun ():"<< Num <<' \ n ';cout<<"The function child thread end...\n";cout<< Endl;}//A function class that implements the operator () methodclassfun{ Public:void operator()(intNUM) {cout<<"The class child thread begin...\n";cout<<"I come from the class fun:"<< Num <<' \ n ';cout<<"The class child thread end...\n";cout<< Endl; }};intMain () {cout<<"Main thread begin ..."<<' \ n ';cout. Sync_with_stdio (true);//Set input stream cout is thread-safeThread T_1 (fun,1);//New thread, the first parameter is a function pointer, the second argument is the function's argument (the second argument is a variable-length parameter)T_1.join ();the number of join methods blocks the main thread until the target thread has finished calling, that is, the join executes the function body portion of the child thread directly.Thread T_2 (fun,2); T_2.detach ();The //detach method does not block any threads, the target thread becomes the daemon thread, and the host background runsFun Ofun; Thread T_3 (ref (Ofun),3);//Create a new thread here, initialize it with an object, where the ofun itself is passed by ref instead of its copyT_3.join ();cout<<"Main thread end ..."<< Endl;return 0;}

Operation Result:

You can see that the main thread is executed first, then the T_1 child thread, then the T_2 child thread, but the t_2 child thread is not finished, and the T_3 child thread is executed, the t_3 executes, t_2 is executed, and then the main thread is finished.
Why would it be such a result? Because T_1 and T_3 call the Join method of thread, T_2 calls the Detach method.
When join () waits for the child thread to execute, the main thread can continue execution, at which point the main thread frees the child thread resources after execution. Detach () separates the child threads from the main thread and becomes a background thread, releasing the resources themselves when the child threads are executed. The main thread will have no control over the disconnected threads.

Thread Synchronization Issues

When it comes to threading, there is always the problem of resource competition and deadlock lock.
C + + provides the atomicity of atomic-hold variables, and personal feelings are somewhat similar to the volatile keywords in Java and C #.
Here's an example:

#include <thread>#include <iostream>#include <vector>using namespace STD;voidFuncint& counter) { for(inti =0; I <100000;    ++i) {++counter; }}intMain () {intCounter =0; vector<thread>Threads for(inti =0; I <Ten;    ++i) {threads.push_back (thread (func, ref (counter))); } for(Auto& Current_thread:threads) {current_thread.join (); }cout<<"Result ="<< counter <<' \ n ';return 0;}

You do a few more times, and you will find that the value of counter per output is not always 1000000 (100000*10=1000000,10 threads, each thread increases by 100000), for what? This involves the competition of resources in multi-threading.
So how do we solve this problem? The atomic class is available in C + + to see the modified program:

#include <thread>#include <iostream>#include <vector>#include <atomic>using namespace STD;voidFunc (atomic<int>& counter) { for(inti =0; I <100000;    ++i) {++counter; }}intMain () {atomic<int> Counter (0); vector<thread>Threads for(inti =0; I <Ten;    ++i) {threads.push_back (thread (func, ref (counter))); } for(Auto& Current_thread:threads) {current_thread.join (); }cout<<"Result ="<< counter <<' \ n ';return 0;}

This executes the above program no matter how many times the output is always: Result = 1000000
In addition, the atomic class also provides some functional operations that are encapsulated, as described in: C + + reference-atomic

Initial C + + multi-threading, just write here.

C++11 Multi-line Cheng experience

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.