1 Why multiple threads
 
The first case is well understood, that is, in multiple CPUs, using multithreading can improve CPU usage.
 
The second case is more common, on a single CPU single core computer, the use of multithreading technology, can also be responsible for IO processing in the process, human-computer interaction and the standing block to the dense calculation of the part of the execution of a dedicated thread execution intensive calculation, thereby increasing the execution efficiency of the program.
 
For example, a network video player, it has the following several tasks need to be processed simultaneously: the network receives the data, the network decodes and plays the video, the corresponding customer on the UI operation and so on. If all of this work is done in a single thread, it's not necessarily impossible, but this single-threaded program can be incredibly complex, and its scalability and readability will be very poor.
 
 
2 Threads and processes
 
A thread is the smallest unit in which the operating system can perform operational scheduling, which is included in the process and is the actual unit of operation in the process.
 
Processes have separate address spaces, and threads do not, so that after a process crashes, it generally does not affect other processes, and if the thread dies, it is basically equal to the entire process being dead, so a multiple process program is more robust than a multithreaded one.
 
Threads have their own registers and stacks, and the same address space is shared between threads, so the efficiency of data communication between threads is much higher and more convenient than interprocess communication.
 
Thread startup takes much less space than the process, so it takes far less time to switch between threads than the process.
 
 
3 Multi-threading programming is difficult
 
Write a multithreaded program is very easy, only a createthread function can be easily done.
 
The difficulty of multithreaded programming lies in the data communication between threads, that is, the access synchronization and protection of shared memory.
 
 
4 Most important principles of multi-threading programming
 
The principle is that all data that may be accessed by multiple threads should be protected with a mutex.
 
All the data mentioned here, including variables, classes, shared memory, and so on.
 
This principle, in turn, is also true, that is, if a variable or cache is determined to be accessed by only one thread, it does not need to be thread-synchronized access protection.