The difference between a process and a thread

Source: Internet
Author: User
Tags mutex semaphore

Originally thought oneself to this aspect should still calculate the understanding, but yesterday was asked unexpectedly can not clear explanation, explanation is very frustrated, today detailed collation of ideas, summarized as follows:
First, we use the simplest sentence to indicate:
process: One execution of the program ;
Threads: The basic unit of CPU scheduling .
In short: A program contains at least one process (for example, we have a client that turns on cool dog music, and in addition to the client process, we see a daemon (the daemon process) in the background, and a process contains at least one thread.

Here I would like to make an analogy first, and then in detail some specific concepts:
Because I grew up in the northeast, high school, to the winter, the most annoying is that once the snow, the school will be assigned a class to the playground to clear the task of snow, here, I put the school analogy into the operating system, and each individual class is likened to a process, the class head of the analogy into the main course, and we each student, is the child thread of the work of the bitter force;
1, first, when the playground covered with snow, the school issued a notice, today it is our turn 30 class (my high school Class) to carry out the playground of the snow-clearing task .

---that the operating system starts running the program, the CPU is assigned to our process, assuming that the single core CPU, the operating system can only run a process at the same time;

2, because the school will not designate a class of which several students to complete the cleaning task, the school will only assign this cleaning task should be carried out by which class.

---that the operating system does not consider multiple threads as separate applications to implement the scheduling and management of the process and the allocation of resources, the process is a program with a certain number of independent functions on a data set on a running activity, the process is the operating system resource allocation and scheduling of an independent unit;

3. then, the head teacher as a leader, began to give us a few students on duty cleaning tasks, who will sweep the northeast corner, who will sweep the southwest corner and so on ,

---that is, when the process starts, the main thread calls Pthread_create to create multiple child threads, the main thread does not work, only responsible for the task scheduling, scheduling to complete the call Pthread_join block itself, waiting for the sub-thread to complete;

4, When we have a few on duty to lead to their respective tasks, in fact, the entire playground is our battlefield, we share this piece of playground, ready to sweat in this playground .

---all the resources owned by the thread-sharing process in a process;

5, because we have been a teacher in charge of the task assigned, we have to clean their own parts, at this time, we happily go to class health corner to clear snow tools, the result of tragic discovery, we 8 people, but only a clear snow shovel, 5 broom, this is embarrassing, how to do? Then, clapped, I have not reacted to, a classmate in the past to the snow shovel to rob Hand, another 5 classmates also no weakness, instant and the broom grab hand, left me and another silly egg, leng in situ, of course, according to reason, class resources we are shared, but snow shovel only one, Can only let the quick reaction of the classmate first use, and so he shovel a shovel tired, I will bring the snow shovel to use.

---The snow shovel here, is a lock, who Rob who to use, in a single-core CPU multi-threaded, the CPU will continue to do context switching to ensure multi-threaded concurrency, (and parallel only exists in the multi-core CPU, multiple CPUs can concurrently execute multiple processes at the same time), In order to ensure that multiple threads read and write to a memory area at the same time, introduce the concept of lock, that is, this snow shovel who get, who will go to clean their own area of responsibility, other threads will put into sleep, and so the person shovel tired, other put sleep thread woke up to scramble for this lock. In addition, five brooms are also a tool for snow, and we can think of it as a "semaphore" (in fact, this analogy is not very appropriate, because "semaphore" is actually an IPC way, is one of the attributes of the lock: process-sharing properties, which are used to coordinate the synchronization primitives of data objects between different processes. It can essentially be seen as a counter), when five brooms are used, the other threads can only put into sleep wait, when the counter plus 1 o'clock, will send a signal to the waiting thread, scramble for the empty "broom", but this "broom" is laborious, work and slow, obviously no "snow shovel" easy to use, so, Should be based on the specific circumstances, to choose whether to use the signal volume or mutual exclusion lock mode;

6, in this way, several of us on duty to the students through the fight for the only snow shovel, eventually continued to shovel their own areas of responsibility, back to class, the class teacher saw me all returned to the class, completed the whole playground of the clear snow task, satisfied with the smile, to the school report, completed today's 30 classes clear snow task.

---The main thread blocks or performs other work concurrently, when the child threads have finished working, the resources of the child thread are recycled and the results of the execution are returned to the operating system.

The above analogy idea comes from Nanyi Teacher's blog: http://www.ruanyifeng.com/blog/2013/04/processes_and_threads.html, and has carried on the related expansion.

Well, the analogy work is done, let's summarize the concepts involved:
process : is a program with a certain independent function on a data set on a running activity, is the OS for resource allocation and scheduling of an independent unit;

thread : is an entity of the process, is the basic unit of CPU dispatch and dispatch, it is smaller than the process can run independently of the basic unit, the thread itself basically does not own system resources, only a little in the running of the necessary resources (such as program counters, a set of registers and stacks), However, it can share all of the resources owned by the process with other threads that belong to one process. (that is, each student has a tool that is the public property of the class, not the public property of the school). One thread can create and revoke another thread, and can execute concurrently between multiple threads in the same process.

Summary of Differences : The main difference between a process and a thread is that they are different ways to manage operating system resources. The process has a separate address space, and after a process crashes, it does not affect other processes in protected mode, and the thread is just a different execution path in a process. Thread has its own stack and local variables, but there is no separate address space between the threads, a thread dead is equal to the entire process dead (for single-threaded case, or the main thread dead), so the multi-process program is more robust than multithreaded programs, but in the process of switching, the cost of large resources, efficiency is worse. But for some concurrent operations that require simultaneous and shared variables, only threads can be used, and processes cannot be used.

In addition, the concept of lock is also mentioned in the analogy, and the following is a brief description of the Apue:
when multiple threads try to modify the same variable at the same time, they need to be synchronized, as an example of adding operations, we are divided into 3 steps:
(1), read the register from the memory unit;
(2), the variable in the register to do incremental operation;
(3), write the new value back to the inner deposit cell.
Note: If the operation is atomic, then there is no competition (because there is no context switch in the middle).
Five ways to synchronize primitives with threads:
(1), Mutual exclusion amount
The mutex is actually a lock, and multithreading locks the mutex before accessing the shared resource, releasing the mutex after the end of the visit. It is only locking and unlocked in both states.
(2), read/write lock
read-write lock in relation to the mutex, there is a state, that is, in the state of lock, there are two types of read and write locks, only one thread at a time can occupy the lock of write mode, but multiple threads can occupy the lock of read mode at the same time. (This is applied in the database)
(3), condition variable
A conditional variable provides a meeting place for multiple threads, and when used with a mutex, allows the thread to wait for a particular condition to occur in a non-competitive manner. The condition itself is protected by a mutex, and the thread must lock the mutex before it changes state, and other threads will not perceive this state until the mutex is acquired, because the mutex must be locked before the condition can be evaluated.
(4), Spin lock
The spin lock does not cause the process to block through hibernation, but is always in a busy, blocked state before acquiring the lock, consumes CPU time during spin, and constantly "asks" if the lock is available so that the CPU cannot switch contexts to do other things. So a spin lock should be applied to a situation where the lock is held for a short time, and the thread does not want to spend too much on rescheduling.
(5), barrier
a barrier is a synchronization mechanism in which the user coordinates multiple threads working in parallel (similar to our join method in Python's threading module, where the parent thread blocks waiting for all the sub-threads to complete the work in the exit, i.e. our "class teacher" in analogy), Pthread_ The join function is a barrier that runs one thread to wait until another thread exits.
This is only a brief introduction, then there is time to detail the synchronization primitives and IPC knowledge.


Reference Blog: http://www.cnblogs.com/lmule/archive/2010/08/18/1802774.html

The difference between a process and a thread

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.