C++11 Concurrent Programming Fundamentals (i): concurrency, parallelism and multithreading in C + +

Source: Internet
Author: User

Body

The C++11 standard provides components for multithreading in the standard library, which means that it is possible to write platform-independent multithreaded programs using C + +, and the portability of C + + applications is strongly guaranteed. In addition, concurrent programming can improve the performance of your application, which is noteworthy for C + + programmers with performance pinching irritate D.

Back to top of 1. What is concurrency

concurrency refers to two or more separate activities that occur during the same time period . There are many examples of concurrency in your life, like when you're running, you may be listening to music at the same time, while your fingers are tapping the keyboard while watching a computer monitor. At this point we call our brains to deal with these events in parallel, except that our brains deal with a secondary focus: Sometimes you pay more attention to the frequency of your breathing, and sometimes you are more attracted to the melody of music. At this point we can say that the brain is a concurrent design structure. this secondary emphasis in computer programming, reflected in a moment can only handle an operation .

Another concept that is similar to concurrency is parallelism . There is a big difference between them. Parallelism is performed simultaneously , and the computer processes two or more operations at a point in time. To determine if a program is executing in parallel, just see if more than two or more units of work are running at some point. If a program is single-threaded, it cannot run in parallel. The use of multi-threading and multi-processes allows a computer to process programs in parallel (assuming, of course, that the computer has multiple processing cores).

    • Concurrency: Multiple operations can be alternately handled during the same time period:

The entire security system in the diagram is a concurrent design structure. Two security queue the first person to compete for this security screening window, two queues may be agreed to alternate security screening, may also be the Competition Security window (communication). The latter approach may cause a conflict: Two security checks cannot be performed at the same time. logically , this security window handles both queues at the same time.

    • Parallel: Handle multiple operations simultaneously at the same time:

The entire security system in the diagram is a parallel system. Here, each queue has its own security window, there is no competition in the middle of the two queues, a queue in the queues just wait for the people in front of the queue to complete security, and then turn to their own security. physically , the security window handles both queues at the same time.

Concurrent programming provides a way for us to devise a solution that solves problems (not must) in parallel. If we design the structure of the program to be executed concurrently, we can execute the program in parallel on a machine that supports parallelism. Therefore, the concurrency focus refers to the design structure of the program, while parallelism refers to the state of the program running. Concurrent programming is a program design method that breaks down a program into small fragments and executes independently.

Back to top 2. Basic ways of concurrency

Multi-threading and multi-process are two ways of concurrency.
Imagine two scenarios:

    • Scenario One: You and the small partner to develop a project, but the small partners in winter vacation are home, you can only through QQ chat, mobile phone calls, send mind map and other ways to communicate, in short you can not easily communicate. The advantage is that you can work independently of each other.
    • Scenario Two: You and your partner stay in the school lab to develop the project, you can get together to use brainstorming, you can use the whiteboard to explain the point of view, in short, your communication becomes more convenient and effective. It's a pity that when you think about it, you may have a little friend come by to ask you a question, and you are disturbed.

These two scenarios depict two basic approaches to concurrency. Each small partner represents a thread, and the work place represents a single processor. Each small partner in scenario one is a single-threaded process that has a separate processor, multiple processes executing simultaneously, and a single processor in scene two, all of which are threads that belong to the same process.

2.1 Multi-process concurrency

Multiple processes run independently, passing messages (signals, sockets, files, pipelines, etc.) through regular communication channels between processes, which are either complex or slow, because in order to avoid a process that modifies another process, the operating system provides some protection between processes, of course, This also makes it easier to write secure concurrent code.
Running multiple processes also requires a fixed cost: The start time of the process and the resource consumption of the process management.

2.2 Multi-threaded concurrency

Running multiple threads in a process can also be concurrent. Threads are like lightweight processes, each of which runs independently of each other, but they share the address space, and most of the data that is accessed by all threads, such as pointers, object references, or other data, can be passed from one thread to another, both of which can access global variables. Memory is commonly shared between processes, but such sharing is often difficult to establish and difficult to manage, and lacks the protection of data between threads. Therefore, in multithreaded programming, we must ensure that the data that each thread lock accesses is consistent.

Back to top of 3. Concurrency and multithreading in C + +

The C + + standard does not provide native support for multi-process concurrency, so the multi-process concurrency of C + + depends on the other api--which relies on the relevant platform.
The C++11 standard provides a new line libraries that includes various classes for managing threads, protecting shared data, synchronizing operations between threads, and low-level atomic operations. Standards greatly improve the portability of the program, the previous multithreading relies on the specific platform, and now has a unified interface to implement.

Several header files are introduced in the new C++11 standard to support multithreaded programming:

    • < thread > : Contains the Std::thread class and the Std::this_thread namespace. The functions and classes that manage threads are declared in.
    • < atomic > : Contains Std::atomic and Std::atomic_flag classes, as well as a set of C-style atomic types and functions that are compatible with C atomic operations.
    • < Mutex > : Contains classes related to mutexes and other types and functions
    • < future > : Consists of two provider classes (std::p romise and std::p ackage_task) and two future classes (Std::future and Std::shared_ Future), as well as related types and functions.
    • < condition_variable > : Contains classes related to condition variables, including std::condition_variable and Std::condition_variable_any.

3.1 Multithreading

Let's start with a hello. On a single thread:

1 # include<iostream>2usingnamespace  std; 3 int Main () 4 {5     cout<<"helloWorld"<<Endl; 6 }

Here, the thread is made up of a thread, the initial function of which is main. We start a second thread to print Hello World:

1# include<iostream>2# include<thread>3 using namespacestd;4 voidHello ()5 {6cout<<"Hello World"<<Endl;7 }8 intMain ()9 {Ten thread T (hello); One T.join (); A}

Here, we place the statement that prints Hello world in the function hello. Each thread must have an initial function, and the execution of the new thread begins with the initial function. For the first program, its initial function is main, which can be specified in the constructor of the Std::thread () object for our newly created thread.
In the second procedure, the program consists of two threads: the initial thread starts at main, and the new thread starts with Hello. This specifies the initial function of the new thread T as hello.
The new thread starts up and runs with the initial process, and the initial thread can wait or not to wait for the new process to end--if a thread waits, the new thread instance needs to use join (), otherwise detach () can be used. If you do not wait for a new thread, the initial thread runs to the end of Main () in its own way.
About < thread > We'll explain in the next article.
Since our initial thread didn't do anything, the new thread would print out Hello world after starting the new thread.

This is the first multithreaded program we've written, and it's generally not worth using multi-threading for such a simple task, especially when the initial thread didn't do anything.

In the next article, we will continue to explore the contents of < thread > header files , and write more complex concurrent programs.

Article Link: http://www.cnblogs.com/QG-whz/p/5186243.html

C++11 Concurrent Programming Fundamentals (i): concurrency, parallelism and multithreading in C + +

Related Article

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.