(1) The difference between multi-threading process
|
Dimension of |
Multi-process |
Multithreading |
Summarize |
|
Data sharing, synchronization |
The data is separate: the complexity of sharing, the need for IPC; |
Multi-threaded shared process data: Easy to share, complex to synchronize |
Each has an advantage |
|
Memory, CPU |
Memory-intensive, switching complexity, low CPU utilization |
Low memory consumption, simple switching and high CPU utilization |
Thread-dominated |
|
Create Destroy, toggle |
Create destroy, switch complex, slow |
Create destroy, switch simple, fast |
Thread-dominated |
|
Programming debugging |
Simple programming and easy commissioning |
Complex programming, complex debugging |
Process-dominated |
|
Reliability |
No interaction between processes |
A thread that hangs up will cause the whole process to hang out |
Process-dominated |
|
Distributed |
Adaptable to multi-core, multi-machine distribution; if one machine is not enough, it is easier to extend it to multiple machines. |
Adaptable to multi-core distribution |
Process-dominated |
Then we'll look at the comparison between the thread and the process.
|
The child process inherits the properties of the parent process: |
Child threads inherit the properties of the main thread: |
|
Actual user ID, actual group ID, valid user ID, valid group ID;
Additional group ID;
Process group ID;
Session ID;
Control terminal;
Set the user ID flag and set the group ID flag;
Current working directory;
root directory;
File mode creates a mask word (umask);
signal shielding and arrangement;
Close (CLOSE-ON-EXEC) flag on execution of any open file descriptor;
Environment
The shared storage segment of the connection;
Storage mapping;
resource constraints; |
All the information in the process is shared for all threads of the process;
Executable text of the program;
The global memory of the program;
heap memory;
Stack
File descriptor;
The processing of the signal is shared by all threads in the process (note: If the default processing of the signal is to terminate the process then the process will be killed by passing the signal to a thread as well);
|
|
Differences between parent and child processes: |
Sub-line thread: |
|
The return value of the fork (=0 subprocess);
The process ID is different;
Two processes have a different parent process ID;
The Tms_utime,tms_stime,tms_cutime and tms_ustime of the child process are set to 0;
File locks that do not inherit the parent process settings;
The unhandled alarm of the child process is cleared;
The unhandled signal set of the child process is set to the empty sets; |
Thread ID;
A set of register values;
Stack
scheduling priorities and policies;
signal shielding word;
errno variable;
Thread-private data; |
1) You need to frequently create priority threads for destruction.
Instance: Web server. To build a thread, break it and destroy the thread. If the process is used, the cost of creating and destroying it is hard to bear.
2) Priority usage threads that require a lot of computation.
The so-called large number of calculations, of course, is to consume a lot of CPU, switching frequently, this situation first thread is the most suitable.
Example: image processing, algorithm processing
3) strong correlation processing with threading, weak correlation processing with process.
What is strong correlation and weak correlation? It is difficult to define in theory, and to give a simple example to understand.
The general server needs to do the following tasks: Messaging and message processing. Messaging and message processing are weak related tasks, and message processing may be divided into message decoding, business processing, these two tasks are relatively more relevant. So messaging and message processing can be divided into process design, message decoding and business processing can be divided into threading design.
4) can be extended to multi-machine distributed with processes, multi-core distributed with threads.
5) Meet the needs of the situation, with the most familiar with you, the most adept way.
As for the "data sharing, synchronization", "Programming, debugging," "Reliability," the dimensions of the so-called "complex, simple" should be how to choose, can only say: There is no clear method of choice. There is a general principle of choice: if multiple processes and multithreading can meet the requirements, then choose the one you are most familiar with.
(2) Multithreading knowledge points
Thread synchronization: Mutex, condition variable, semaphore, read/write lock
1> Mutex: Only one thread is allowed to enter the critical code within one time
Related interfaces:
Pthread_mutex_init ();
Pthread_mutex_lock ()
Pthread_mutex_trylock ()
Pthread_mutex_unlock ();
Pthread_mutex_destory () (this time the lock must be unlock state)
2> condition variables: The use of sharing a global variable between threads is the implementation of synchronization, the basic operation is: trigger conditions (when the condition is true), wait for the condition, suspend the thread until the other thread triggers the condition
Related interfaces:
Pthread_cond_init ()
Pthread_cond_wait ()
Pthread_cond_timewait ()//Timed Wait
No matter what kind of waiting to use with a lock, to prevent multi-threaded simultaneous request competition conditions
Pthread_cond_singal ()//activating a thread
Pthread_cond_broadcast ()//Activate all threads
Pthread_cond_destory ()//No thread is destroyed while waiting, otherwise ebusy is returned
General usage:
Pthread_mutex_lock ();
Pthread_cond_wait ();
Pthread_mutex_unlock
Guess pthread_cond_wait Source:
int pthread_cond_wait (pthread_cond_t *cond,pthread_mutex_t *mutex)
{
if (no condition variable)
{
(1) Pthread_mutex_unlock (mutex);
(2) blocking the current thread, waiting for a signal (it should be a wait mode similar to interrupt triggering instead of software polling)
(3) Pthread_mutex_lock ()
}
......
}
3> Semaphore: Same as the signal volume of the process
Related interfaces:
Header Files <semaphore.h>
Sem_init (sem_t *sem,int pshared,int value); Pshared=0 (only 0 under Linux), for process local semaphores
Sem_post (sem_t *sem)//signal volume plus 1 v operation
Sem_wait (sem_t *sem)//signal volume minus 1 p operation
Sem_destroy (sem_t *sem)
4> read-write Lock: Multiple read locks can share a critical section, write lock and write lock mutex, write lock and read lock mutex
Related interfaces:
Pthread_rwlock_init ()
Pthread_rwlock_rdlock ()
Pthread_rwlock_wrlock ()
Pthread_rwlock_unlock ()
Pthread_rwlock_tryrdlock ()
Pthread_rwlock_trywrlock ()
Pthread_rwlock_timerdlock ()
Pthread_rwlock_timewrlock ()
Pthread_rwlock_destroy ()
Extension: Spin lock
(1) Request lock, not requested, has been busy waiting until the request to this lock, no context switch
(2) Possible deadlock: Recursive invocation, critical section causes blocking
(3) Use scene: Lock holding time is short
(4) The relationship between spin lock and Linux kernel process scheduling
The critical section of the spin-lock protection works in a non-preemptive state, even if the lock is not acquired, the "spin" state is also forbidden to preempt, re-open preemption at Spin_unlock
Summarize:
1> single-CPU non-preemptive: Spin lock is ignored at compile time (because no process switching occurs, only one process or thread is in the critical section, the spin lock is not used)
2> single CPU preemption: Spin lock only as a set preemption switch (because the single CPU does not involve concurrent access, setting the prohibit preemption can guarantee that the critical section is unique)
3> Multi-CPU: Prevents concurrent access by multiple processes, preventing kernel preemption from competing
Thread Safety: Atomic operations, locks, reentrant, preventing over-optimization
Atomic operation: To ensure that the direction of the directive atom is not interrupted, the Linux system provides some common operations of atomic instructions, <ATUOMIC.H>, including atomic integer manipulation and atomic bit manipulation, must be an integer of type atuomic_t (32-bit integer, 24-bit data, 8bits of Lock)
Lock: Mutually exclusive access to the critical section code
Reentrant: That is, it can be interrupted and entered again with no effect, which means that it does not depend on any environment (including static) in addition to the variables on its own stack
Prevent over-optimization: we can use the volatile keyword to try to block over-optimization, and it can do two things: first, prevent the compiler from caching a variable to register instead of writing back in order to increase speed, and second, prevent the compiler from adjusting the order of instructions that manipulate the volatile variable.
Non-latching programming:
For counters, you can use atomic Plus
There is only one producer and one consumer, so you can do a lock-free access to ring buffers (ring buffer)
RCU (read-copy-update): A new and old replica switching mechanism that can take deferred release practices for old replicas. Principle: for shared data structures that are protected by RCU, the reader does not need to acquire any locks to access him, but writes a copy before accessing it, then modifies the copy, Finally, a callback (callback) mechanism is used to re-point the pointer to the original data at the appropriate time to the new modified data. This is the time when all the CPUs referencing the data exit the shared data structure operation. The writer does not need to compete with the reader for any locks when accessing the shared data structure, and only requires synchronization in the case of more than one writer. the core of RCU technology is writing and updating two steps
CAS (compare-and-swap):
The CAS primitive is responsible for comparing the value of a memory address (1 bytes) to an expected value, and if it is equal, substituting the value at that memory address with the new one, the CAS operation Pseudo-code is described as follows:
Bool CAS (t* addr, t expected, T newvalue) {if (*addr = = expected) {*addr = newvalue; return true;} else return false; }
(3) Multi-process knowledge points
Multi-process communication: pipelines, Named pipes, message queues, shared memory, sockets
The difference between multi-threading and multi-process