C ++ std :: thread python introduce the concept of multi-threaded and multi-process and multi-thread synchronization difference python case study

11 new C ++ standard, the official language for the introduction of the concept of multi-threading. The new standard provides a thread library thread, by creating a thread object to manage multi-threaded C ++ program.

This paper briefly talk about some basic C ++ multi-threaded usage of related concepts and thread.

0. executed in parallel

Two necessary conditions for parallel execution:

  • Multi-processor (multiple processors) or multi-core processor (multicore processors)
  • Parallel Software

Concurrent execution of software can be divided into two categories:

  1. Multi-threaded (multiple threads in parallel with a process);
  2. More complicated process (different processes in parallel);

For multi-threaded, the main concern is synchronized measures between threads for thread-safe;

For multi-process, the main concern is inter-process communication mechanism, used to pass messages and data between processes;

Because the C ++ standard is not relevant standard for communication between multiple processes, which can only rely on platform-specific API. This article focuses on multi-thread-related.

1. C ++ multi-threaded platform

C ++ before 11, window and linux platform, respectively, have their own multi-threaded standards. Using multiple threads written in C ++ is often tied to a particular platform.

  • Window platform for multi-threaded win32 api created and managed;
  • Under Linux, there are multi-threaded API POSIX standard, Threads or Pthreads library provides classes can be run on Unix;

In the new C 11 ++ standard, you can simply by using hread library to manage multiple threads. thread library can be seen as a wrapper for different platforms, multi-threading API;

Therefore, programs that use the new standard library provides is written in cross-platform.

2. pthread 或 C++ 11 thread

pthreads threading library is C ++ under linux, provides some threads related to the operation, in favor of the underlying operation of the thread is more direct and convenient;

#include <pthread.h>
pthread_create (thread, attr, start_routine, arg) 

For the linux pthread pthread library needs to be connected (Editor may require some -std = c ++ 11):

g++ source.cpp -lpthread -o source.o 

Although there are many online for Tucao 11 new standard C ++ class in the thread, but as the first C ++ standard thread library, there are some areas worthy of recognition, such as cross-platform, easy to use.

And the new standard can easily use RAII to achieve lock of management.

If you want in-depth look at the multi-threaded, so pthread is a good choice. If you want to achieve cross-platform or multi-threaded some simple scene without too much attention to detail, the authority of the standard library thread is the best choice.

In short there is no good or bad points, it fits just fine. If you can find out all you can. This paper describes the latter.

3. After the first practice theory

For multi-thread-related learning, some of the concepts be clear thread-related, is very important.

Such as thread-safe, thread synchronization relationship with a mutually exclusive relationship, how threads communicate with the process of such a system.

Otherwise, the actual writing multithreaded programs is run into too many problems, such as:

  • Deadlock, no response;
  • The results do not meet expectations;
  • Multi-threaded performance is not improved so much;
  • Disarray program execution process;
  • I do not know how to debug;
  • Good times and bad program runs;

Light-safe, there are many theories to understand that these alone debugger, according to the results to guess is not feasible.

About related to the concept of threads can refer to my previous example to introduce Python threads Bowen:

Example 4. thread multithreaded

Look at the example ++ 11 standard library thread to create multi-threaded C:

 1 #include<iostream>
 2 #include<thread>
 3 #include<string>
 4 
 5 using namespace std;
 6 
 7 int tstart(const string& tname) {
 8     cout << "Thread test! " << tname << endl;
 9     return 0;
10 }
11 
12 int main() {
13     thread t(tstart, "C++ 11 thread!");
14     t.join();
15     cout << "Main Function!" << endl;
16 }

Multithreading standard library objects using a thread to manage the thread produced. In this example, t indicates the new thread object thread.

4.1 standard library way to create threads

Open thread header file, you can clearly see the constructor thread provided.

  1. Default constructor thread (noexcept); 
  2. Receiving template constructor function and passing parameters <class _Fn, class ... _Args, ...> explicit thread (_Fn && _Fx, _Args && ... _Ax)
  3. move构造函数                                       thread(thread&& _Other) noexcept;
  4. Copy constructor thread (const thread &) = delete;
  5. Assignment operator copies thread & operator = (const thread &) = delete;

Wherein the copy constructor and assignment operator copies are disabled, meaning std :: thread objects can not be copied and assigned to another thread object;

The default constructor Constructs an empty thread object, but does not represent any thread;

The constructor accepts parameters Creates a thread object, the thread begins execution from the incoming function of the object is joinable;

move constructor can be seen as a thread object control authority thread to another thread object; after the execution, the incoming thread object does not represent any thread;

int main()
{
    int arg = 0;
    std::thread t1;                        // t1 is not represent a thread
    std::thread t2(func1, arg + 1);     // pass to thread by value
    std::thread t3(func2, std::ref(arg));  // pass to thread by reference
    std::thread t4(std::move(t3));         // t4 is now running func2(). t3 is no longer a thread
    //t1.join()  Error!
    t2.join();
    //t3.join()  Error!
    t4.join();
}

In most cases it is to create a second thread above the way we use. The following look at the join and detach.

4.2  join && detach

For thread creation, the general calls the join and detach function before its destruction;

It calls to figure out the timing and significance of these two functions, as well as before and after the calling thread state is very important.

  • join the current thread will block until the target thread is finished;
    • Only active threads can call join, can () function checks by joinable;
    • joinable () == true indicates that the current thread is active threads can call the join function;
    • The default constructor creates an object is joinable () == false;
    • join only be called once, after joinable will become false, it indicates that the thread is finished;
    • Call ternimate () thread must be joinable () == false;
    • If the thread does not call join () function, even if the activity is finished is a thread that is joinable () == true, you can still call the join () function;
  • detach the thread object and represented by a thread separation;
    • Call detach objects represent thread and thread it represents complete separation;
    • After separation of the thread is not constrained and regulated, it will perform alone, until the finished release resources, can be seen as a daemon thread;
    • After separation thread objects no longer represent any thread;
    • After separation joinable () == false, even if still running;

join Case Study :

int main() {
    thread t(tstart, "C++ 11 thread!");
    cout << t.joinable() << endl;
    if (t.joinable()) t.join();
    //t.detach(); Error
    cout << t.joinable() << endl;
    // t.join(); Error
    cout << "Main Function!" << endl;
    system("pause");
}

Simply the only thread is active before they can call join, call returns indicates that the thread is finished, joinable () == false.

inline void thread::join()
    {    // join thread
    if (!joinable())
        _Throw_Cpp_error(_INVALID_ARGUMENT);
    const bool _Is_null = _Thr_is_null(_Thr);    // Avoid Clang -Wparentheses-equality
    ... ...
}

The above t.join () is replaced t.detach () get the same result.

void detach()
    {   // detach thread
    if (!joinable())
        _Throw_Cpp_error(_INVALID_ARGUMENT);
    _Thrd_detachX(_Thr);
    _Thr_set_null(_Thr);
    }

The above is a thread defined in the file to detach, we can see only joinable == true thread (), which is the active thread can call detach.

~thread() _NOEXCEPT
    {   // clean up
    if (joinable())
        _XSTD terminate();
    }

When a thread calls neither join nor detach call, the thread is finished joinable () == true, then when the thread object is destroyed, it will call terminate ().

4.3 get the thread ID

Thread is a thread identifier ID, C ++ standard provides two modes obtain the thread ID;

  1. thread_obj.get_id();
  2. std::this_thread::get_id()

One thing to note is empty thread object, that is, does not represent any thread thread obj call get_id returns a value of 0;

Further, when a thread or detach joinable () == false, get_id call returns 0 results.

cout << t.get_id() << ' ' << this_thread::get_id() << endl;
//t.detach();
t.join();
cout << t.get_id() << ' ' << std::this_thread::get_id() << endl;

4.4 exchange thread thread representation

In addition to detach the thread described above can be isolated and represented by the thread object, or move to another thread, you may also be used to exchange swap thread object represented by two threads.

Examples of exchanging a look at the two threads.

int tstart(const string& tname) {
    cout << "Thread test! " << tname << endl;
    return 0;
}

int main() {
    thread t1(tstart, "C++ 11 thread_1!");
    thread t2(tstart, "C++ 11 thread_2!");
    cout << "current thread id: " << this_thread::get_id() << endl;
    cout << "before swap: "<< " thread_1 id: " << t1.get_id() << " thread_2 id: " << t2.get_id() << endl;
    t1.swap(t2);
    cout << "after swap: " << " thread_1 id: " << t1.get_id() << " thread_2 id: " << t2.get_id() << endl;
    //t.detach();
    t1.join();
    t2.join();
}

result:

Thread test! C++ 11 thread_1!
Thread test! C++ 11 thread_2!
current thread id: 39308
before swap:  thread_1 id: 26240 thread_2 id: 37276
after swap:  thread_1 id: 37276 thread_2 id: 26240

Here is the thread :: swap function.

void swap(thread& _Other) _NOEXCEPT
    {   // swap with _Other
    _STD swap(_Thr, _Other._Thr);
    }

We can see the process of exchange of the swap is only held by the underlying thread object handle;

About C ++ multithreading basic introduction to the new standard thread on here, and see that there should be a simple met.

About thread safety and other senior management topics, behind free writing article describes.

Guess you like

Origin www.cnblogs.com/yssjun/p/11533346.html