C ++ 11 concurrent programming entry

  Some people may think and launched an attack with multi-threading and complex, but also make the code a variety of problems, but in fact it is a powerful tool that allows the program to fully utilize the hardware resources so that programs run faster .

What is complicated by:

  Two or more independent activities have to occur simultaneously. The computer is a single system simultaneously perform multiple independent tasks, by doing this task for a while, then switch to another task to do for a while, which allows the task appears to be executed in parallel. Switching context switching is done, there will be time cost, saving CPU operating system is currently running task status and pointer where you want to switch to calculate a task, and the task for the upcoming switch to reload the processor state.

Concurrent way:

  Concurrent multi-threaded multi-process

  More complicated process:

  Similarly the same time, run a web browser, QQ, word this way belong to more complicated process. Between processes communicate through pipes, sockets, files, and other means.

  Multithreading:

  Run multiple threads in a single process. All threads in the process shared address space.

Why Concurrency:

  1: Separation of Concerns

  2: Improving Performance

When Not to Use Concurrent:

  Basically, the only reason not to use concurrency is, not as cost benefits. Using concurrent code in many cases difficult to understand, so to write and maintain multi-threaded code produces an immediate mental costs and additional complexity may also lead to more errors. Unless the potential performance gain is large enough or separation of concerns to clear enough to offset the required extra development time and maintenance associated with multithreaded code extra cost (under the code correct premise); otherwise, do not use concurrency. In addition, the thread is a limited resource. If you let too many threads running at the same time, the operating system will consume a lot of resources, so that run more slowly on the operating system as a whole.

A simple example of concurrency:

Hello.cpp // 
#include <the iostream> #include <Thread> // support multithreading header the using namespace STD; void thread_func () // child thread entry function { COUT << " Hello Thread " << endl; } int main () { thread my_job (thread_func); my_job.join (); // main thread like child thread is finished before continuing with the COUT << " Hello main " << endl; return 0 ; }
# CMakeLists.txt
cmake_minimum_required(VERSION 3.5.1)
set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -march=native -O3 -pthread" )
project(thread_test)
add_executable(thread_test1 hello.cpp)

 

Guess you like

Origin www.cnblogs.com/418ks/p/11570363.html