C++11 Concurrent Programming

Source: Internet
Author: User
Tags thread class

C++11 began to support multithreaded programming, before multithreaded programming requires system support, the creation of threads under different systems requires different APIs such as Pthread_create (), CreateThread (), Beginthread () and so on. Now C++11 introduces a new line libraries, C++11 provides a new header file that mainly includes <thread>, <mutex>, <atomic>, <condition_varible>, < Future> Five part;<thread> is used to support multi-threading, and includes many tools for starting and managing threads, as well as a synchronization mechanism including mutex, lock, atomic weight, etc. In this series of articles, I will try to share with you some of the features that this new library provides

in order for your code to support multi-threaded libraries, your environment compiler must support c++11, but fortunately the majority of compilers now support c++11, unless you are on hand the compiler version is an antique level, it is true, it is recommended that you upgrade quickly, Not only for this study, you will definitely use the back.

Benefits of Multithreaded programming

Before looking at this article, if there are doubts about what a thread is, what is a process, Google first, these two concepts are not within the scope of this article. Use multithreading only One of the purposes is to make better use of CPU resources, the following two graphs are a good response to this.

Take a single CPU, for example, if there is a process, the process function is to accept data from the network, the received data processing. We know that the data on the network has a delay, even in the time you receive the data due to the network and other problems to receive data, if it is a single-threaded process , then your process can do nothing at this time, struggling to wait for the data on the end. At this point the CPU is wasted (assuming that the system does not consider switching processes to other processes on this process).

If a process contains two threads, a thread is specifically receiving data, called a thread, and another thread is specifically responsible for processing the received data, called the B thread. Then the situation is not the same, when the network and other problems when the data is blocked only a thread, can be a certain scheduling mechanism to the CPU to the B-thread to let it work. In this way, the CPU gets the most out of it and is not wasted there.

Well, since the use of threads is so large, C++11 has added support for multi-threaded libraries, so let's get a glimpse of it.

How to start a thread

In C++11, starting a new thread is very simple, and when you create an instance of Std::thread, it starts on its own. At the same time, when you create a thread instance, you provide a function that the thread is about to execute, and one method is to pass a function pointer on the CREATE thread instance.

Well, no matter what programming language you're learning, Hello world! feels like it's always going to be a standard. This time we are still using the classic "Hello World" example to create a thread for you:

 #include  <thread> #include  <iostream>void hello () {    std::cout  <<  "hello world from thread !" &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;<<&NBSP;STD:: Endl;} Int main () {    std::thread t (hello);     t.join ();     return 0;} 
[Email protected] c++]# g++-std=c++11-o a a.cpp[[email protected] c++]#./aterminate called after throwing an instance of ' std::system_error ' What (): Enable multithreading to use std::thread:operation not permitted abandoned

Cloud line times wrong, compile the time add-lpthread

[Email protected] c++]# g++-std=c++11-lpthread-o a a.cpp[[email protected] c++]#./ahello World from Thread!

See, first of all, we introduced the header file <thread>. In this header file, C++11 provides classes and functions for managing threads. After that, we define a function hello with no return type, which does nothing except print a line of text in the standard output stream. Then, we define a variable t of type Std::thread, which, when defined, uses the name of the Hello function (which is actually a function pointer) as the parameter of the Std::thread class constructor.

Notable in this example is the function join (). Calling join () causes the current thread to wait for the join thread to end (in this case, the thread main must wait for the thread T to end before it can continue execution). If you do not call join (), the result is undefined-the program may print "Hello World from Thread" as you wish and a newline, but it may print only "Hello World from Thread" without wrapping, not even anything. Do, that is because the thread main may have returned before the end of the line T.

The second thing to note is that you need to add the parameter -std=c++11when compiling, otherwise compile.

To start a thread with a lambda expression

If the code that the thread is going to execute is very short, you have absolutely no need to create a function specifically for it, instead of using a lambda expression (about lambda expressions, interested friends can surf the internet to check its usage, which is also a new feature of c++11). We can easily rewrite the above example to use the form of a LAMBDA expression:


#include <thread> #include <iostream>int main () {Std::thread T ([] () {std::cout << "Hello World F ROM Thread! "       << Std::endl;});    T.join (); return 0;}

[[email protected] c++]#./b

Hello World from Thread!

As above, we used a LAMBDA expression to replace the original function pointer. There is no doubt that this code implements exactly the same functionality as the code that previously used the function pointer.

add parameters to your thread execution function

Do you think it's a bit of a fuss to open a thread just to print a word, OK, we should do something now. On the basis of the last thread function, in addition to printing a word, we add a function: Accept two parameters, calculate their and and print out.

 #include  <thread> #include  <iostream>//thread execution function accepts two int type parameter Void hello (int x,int  y) {   std::cout<< "hello world from thread !"  <<std::endl;   std::cout<< "x+y=" &NBSP;<<X+Y&NBSP;<<STD::ENDL;} Int main () {  std::thread t  (hello,10,20);   t.join ();   return  0;} 
[[email protected] c++]#./C
Hello World from Thread!
X+y=30

The running result of the program is exactly what we want, yes, the argument to the thread function is as simple as passing the past with the function pointer when creating the thread instance

thread-sensitive

> We can go back to how we distinguish processes? Each process has a number, called the PID (process ID), we are through it to distinguish between different processes, not only our people, in fact, the operating system is also through this PID to distinguish between the management of different processes.  

#include  <thread> #include  <iostream> #include  <vector>void hello () {        std::cout <<  "Hello world from thread:   "               << &NBSP;STD::THIS_THREAD::GET_ID ()                 << std::endl;} Int main () {    std::vector<std::thread> threads;     for (Int i = 0; i < 6; ++i)     {          threads.push_back (Std::thread (hello));    }     for (auto& thread : threads)     {         thread.join ();     }   return 0;}
[[Email protected] c++]# ./threadhello world from thread: hello world  from thread: Hello world from thread: Hello world from  thread: 140598791485184140598816663296140598799877888hello world from thread:  140598783092480hello world from thread: 140598774699776140598808270592[[email  protected] c++]# ./threadhello world from thread: 140198417712896hello  world from thread: 140198409320192hello world from thread:  140198392534784hello world from thread: 140198375749376hello world from  thread: 140198384142080hello world from thread: 140198400927488

See, I'm sure this is not what you want to see, the results seem confusing, if you run more than one time on your computer, and even other results, then what is the cause of this incredible running results?

We know that the threads are cross-running, and in the above example, we do not control the order in which the threads are executed, a thread may be preempted at any time during the run, and we can see that the ostream of the example above is divided into several steps (first outputting a string, then the ID, and finally the line wrapping). Therefore, three threads may have performed only the first step to print the Hello world from thread, and then each thread executes the remaining two steps (print ID and then line break), which results in the above running result.

Then there is no way to solve the above problem, the answer is yes, next we will see how to use the lock mechanism to control the execution order of threads .

#include  <thread> #include  <iostream> #include  <vector>pthread_mutex_t   lock = pthread_mutex_initializer;void hello () {        Pthread_mutex_lock (&lock);            std::cout  <<  "hello world from thread: "         &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&LT;&LT;&NBSP;STD::THIS_THREAD::GET_ID ()                 << std::endl;     pthread_mutex_unlock (&lock);} Int main () {    std::vector<std::thread> threads;     for (Int i = 0; i < 6; ++i)     {          //pthread_mutex_lock (&lock);     &nbsP;   threads.push_back (Std::thread (hello));         // Pthread_mutex_unlock (&lock);     }    for (Auto& thread  : threads)     {        thread.join ();     }   return 0;}

[Email protected] c++]#/threadhello World from Thread:140515972613888hello World from Thread:140515939043072hello wor  LD from Thread:140515930650368hello World from Thread:140515964221184hello to Thread:140515955828480hello world From Thread:140515947435776[[email protected] c++]# Thread:140654524454656hello Ead:140654532847360hello World from Thread:140654516061952hello World from Thread:140654507669248hello World from Threa D:140654499276544hello World from thread:140654490883840

See no, now execute the thread program, it will not be messy.

Reprinted the Code of farming Youdao, and put the latter part of the completed.


C++11 Concurrent Programming

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.