C ++ 11 standard native multithreading

It is called the native C ++ 11 standard multi-threading, because in C ++ C ++ 11 version before adding multithreading. The so-called native language is C ++ native, different from other library implementation, such as POSIX, Boost, winAPI, QT [contempt rarely mentioned multithreaded QT, but because I want to use QT multithreading library, was seriously learning C ++ 11 standard native multi-threaded. ], And other multi-threaded implementation. Learning about the system C ++ native multi-threaded programming book, I recommended by Anthony Williams's book "Cpp Concurrency In Action", the Chinese version translated by Chen Xiaowei. Anthony Williams is a multi-threaded C ++ 11 standard drafting with one.

"C ++ Concurrency in Action" Chinese version of online access to Chen Xiaowei read the gitbook, he is a free open source.

About Concurrent

"C ++ Concurrency in Action", a book popular explanation for the concurrent: The simplest and most basic concurrent, refers to two or more separate events occur simultaneously.
Concurrency can be seen everywhere in life, we can walk and talk, you can make two hands at the same time different actions, as well as each of us to live independent lives - when I was in swimming, you can watch the game ,and many more.

Why Concurrency : "C++ Concurrency in Action" described in somewhat abstract, somewhat esoteric. Popular speaking, is that we want to do more things at the same time: the focus (SOS) [We do,] the separation task. There is, we hope to improve my performance by concurrently . The purpose of concurrent always occur in both cases.

 

C ++ Concurrency and multithreading

Before C ++ 11 standard out, using C ++ to develop concurrent programs had to rely on third-party libraries implement, or support system API environment. These can not be the perfect support for platform-independent scalable multi-threaded development. C ++ 11 has brought amazing changes in the native provides standardized support for multithreading. About multi-threaded C ++ history, recommended reading "C ++ Concurrency in Action" section 1.3.1 content.

I am using QT development, QT5 series version of the multi-threading support relies on native C ++ 11 standard multi-threading. QT6 upcoming series should fully support the C ++ 17 standard. It is necessary to look at the system C ++ native multithreading 11. This understanding QT multi-threaded development will achieve a deeper understanding. Of course, the QT environment, we can ignore the native multi-threaded development in C ++. Because even native C ++ and QT packaged multi-threaded programming interface, or also other libraries, which are substantially not change much. And understanding the standard, the best way to develop multithreaded other libraries are also knocking.

 

process

Process (Process) is a computer program run on a set of data on the activities of the system is the basic unit of resource allocation and scheduling, is the underlying operating system architecture. In the computer architecture for the early design process, the basic process is the execution of the program entity; in contemporary computer architecture design for the thread, the thread is the process vessel. Program is instruction, organization of data and its description of the process is a solid program.

Popular thing about is that we are running in a computer or mobile phone in every program, every process is a solid program. Since each process is the entity running the program, and that each program at least there is a separate process (of course, some programs may create multiple processes, such as in the figure below Baidu network disk), and between processes are independent of each other existing. As we are running: cool dog music, Baidu network disk, WPS and so on, when we listen to songs, while also writing office documents, the work of these at the same time are carried out independently. And each is a work in progress in the implementation of a separate process. Process is managed by the operating system maintenance, so the process of resource overhead relative to the thread bigger. This is also the application will be more inclined to develop a thread of reason.

If we open the windows task manager we will see:

Thread

Thread (English: the Thread ) is the smallest unit of an operating system capable of operation scheduling. It is included in the process, the actual operation of the unit process. A thread refers to a single control flow of a process sequence, a process can be complicated by a plurality of threads, each thread in parallel to perform different tasks. In the Unix System V and SunOS it is also referred to as lightweight processes ( Lightweight Processes ), but more lightweight process refers to kernel threads ( Kernel the Thread ), while the user thread ( the User the Thread ) called threads.

A thread is the basic unit of scheduling and dispatching of independence. For the operating system kernel threads can be scheduled kernel threads, such as Win32 threads; voluntarily by the user process scheduling user threads, such as the Linux platform, the POSIX the Thread ; or mixed scheduled by the kernel and user processes, such as Windows 7 thread.

The same process multiple threads to share all system resources of the process, such as virtual address space, file descriptors, and signal processing, and so on. However, multiple threads in the same process has its own call stack ( Call Stack ), register your environment ( the Register context ), own thread local storage ( the Thread-local Storage ).

A program can have one or more processes, a process can have a lot of threads. Because the process and the process is independent of each other, so communication and information sharing between the process would be cumbersome and difficult to achieve. So most of the application is multi-threaded more choices. Each thread in parallel to perform different tasks. Even so multi-threaded development is not a simple matter, because he is related to many of the concepts and traps. For example, pre-Bug singleton pattern in the year occur in use for a long time only to find later.

In the multi-core or multi- CPU , or support Hyper-threading the CPU benefits of using multi-threaded program design is obvious, is to enhance the throughput execution of the program. In a single CPU on a single core computer, the use of multi-threading technology, the process can also be responsible for I / O processing, human-computer interaction and often blocked part of the computationally intensive part of the implementation of separate, written specifically for workhorse thread performing intensive calculation, thereby increasing the efficiency of the implementation of the program.

My understanding is that the thread: A thread is a sequence of instructions, in order to accomplish a single task. Therefore, a thread is serial tasks.

 Multithreading

Multithreading (English: multithreading ), it refers to the realization of multiple threads from a software or hardware concurrent technical implementation. A computer with multi-threading capability due to hardware support and can execute more than one thread at the same time, thereby enhancing the overall processing performance. The system with this capability include a symmetric multi-processor, multi-core processors and chip-level multiprocessing ( Chip-Level multithreading ), or simultaneous multithreading ( Simultaneous- multithreading ) processor. In one procedure, these fragments separate running programs called "thread" ( the Thread ), it is programmed to use the concept called "multi-threading ( Multithreading )."

I understand: Multithreading is multiple threads execute in parallel tasks. More popular point is that several serial tasks in parallel, at the same time, simultaneously perform multiple tasks serially.

I understand: Concurrency is not necessarily simultaneously. In the era of single-core CPU, more of an illusion. To unify all processes, according to a certain order a slice of a serial algorithm execution. Concurrency is more of a concept, it refers to the beginning of the task at the same time, but not necessarily parallel. And now in the era of multi-core, often accompanied by concurrent parallel, but not necessarily exactly. My understanding is this: program (process) running on the computer more often than the core number of computers, the number of threads in the process obvious bear will be more. As a result, CPU can not provide us with so many parallel computing. Still have to return to single-core algorithm execution times. As a result, the so-called parallel and sometimes also an ideal concept. Its purpose and the purpose is not to become.

Of course there is a possibility that on some systems, processes at a certain time to get all the permissions to perform core CPU, this time if the thread is still more than the CPU core, it is likely to still be some serial execution.

Some information that, multithreading is absolutely parallel. From the analysis point of view this is wrong. Also add that that thread is a unified operating system execute permissions are assigned. Therefore, programmers at most it can only control the internal thread control program. The system arrangement of threads, the programmer is powerless.

Before implementing a thread issues to consider: security thread

In a single-threaded execution environment, or whether the thread is suspended because some signal interruption in operation, no matter how this thread to access the variables it holds and resources, we will follow to write code to secure the execution (thread-safe ).

If multiple threads, we can imagine, two or more threads simultaneously access a method, but this method does not affect external data, only affect the local variable inside the function. It should still be safe (unless we care data between the data generated by these processes call this method returns have relevance). The problem is that if the way we access will affect global data, or persistent data in the database. Security problems will become apparent. We call thread-safe objects or methods are stateless. Conversely, multithreading method or objects are state. [My understanding of the state and have no state are: No state does not affect the external data, only affect the local variable data they produce. There will affect the state information data externally, and the external object or a property associated. ]

Thread-safety issues, for example : Our program requires a special class that can create an object in the entire program, if you have to instantiate an object, we do not allow re-creation ( Design Patterns: Singleton pattern ) . We will first use if object == nullptr determine whether the object has been created, if you've created, we do not need to create objects again. It would appear that everything is very harmonious and beautiful, exactly what we desired results. Ideal after all is ideal, when one process (we call A when the process) to determine the object has not been created, this class will call the constructor method of the class, began to create the object. Can, then another process (we call B process) just need an object instance of this class, the management function will determine whether the class has been created object instance, then if process A process is still created, no created object instance. Then process B is considered not create an object instance, have begun to create an object instance. The final result is that the two processes have created this special class of object instances, causing the result is not what we need. At this time not just did not perform according to our reservation result, there will be more unpredictable erroneous results, as well as memory leak may occur. This is the thread safety problems. This is just one example of the classic single-mode multi-thread-safety issues. If the banking system deposits, withdrawals program, will still produce thread-safety issues. Appendix "C ++ Concurrency in Action" book has a full multi-threaded example ATM.

 

How to implement threads: Start a new thread

<Thread> header file provides the tools to manage and identify the threads and provides a function that allows the current thread to sleep.

std :: thread class is in the <thread> header, std :: thread class is used to perform thread management. It provides create, start or perform, but also to provide identification of the thread, and provide other functions for managing threads of execution. So for the management of multi-threaded C ++ we just need to focus on functionality <thread> header file provided.

Entrance thread: We know that the thread is the smallest unit of execution of the application process. Therefore, an application that at least there will be a process, and the process also will have at least one thread exists. An application by the main () function to start the application of resources to support the process started by the entrance of the operating system. And after initialization process is completed, the real essence of it is handed over to the operating area complete with thread. By the main thread function start (), which we call the main thread or the original thread . Other threads (if we need a new thread) we need to achieve their entry function (in C ++ standard, of course, is to call std :: thread class).

Creating a simple start thread : in fact we have one thing very clear, the thread is a task. When the task work is finished, the task (thread) also finished. In other words, the work of a thread (task) to be performed Once finished, this thread (task) will automatically end.

Create a new thread in C ++ is to construct std :: thread object when we construct an empty std :: thread object, which we have created the equivalent of a no-space missions substantive work. Of course, we create an empty task, did not make any sense. So we have to tell std :: thread objects (this new process [task]) need to do what the actual point. Need to make the work may be a function of the method, it may be an object, and so on.

Therefore, our code is as follows:

//我们提供一个函数交给一个新线程(新的任务)去执行
void do_some_work();
std::thread my_thread(do_some_work);

This is one of the most pure new thread, we have become simple. Because we submitted to the new thread (new task) work is a simple function method.

But when we give this new thread (new task) dispatched work is an object method, we must tell the new thread (new task) method is the object whose method. This is what we have to pass an object to be aggressive.

Note: This is for new to std :: thread constructor friends will be a little confused. Most likely you will create a class in a new process, and then calls the class inside the way for the new thread to execute. We might write this code.

//假如我们在一个Connection类里
//threadA是Connection类里的方法

std::thread t(&Connection::threadA);  //很多C++编辑器,不会给你发出警告,直到运行时才会发生错误。
t.join();


//刚使用的朋友,更可能会这样写
std::thread t(this->threadA);  //这时编辑器会给你亮出语法错误
t.join();

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Published 17 original articles · won praise 1 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_40583088/article/details/104125900