19-python-Processes and Threads

Source: Internet
Author: User
Tags mutex

1. Process

The program does not run alone, and the program is assigned resources to run only if it is loaded into memory, and this execution is called a process. The difference between a program and a process is that a program is a set of instructions, which is a static descriptive text of the process, and a process is an execution activity of a program, which belongs to the dynamic concept.

In multi-channel programming, we allow multiple programs to be loaded into memory at the same time, which can be implemented concurrently under the dispatch of the operating system. This is the design that greatly improves the CPU utilization. The advent of the process makes it possible for each user to feel the CPU alone, so the process is proposed for multi-channel programming on the CPU.

Why do threads still have a process?

The process has many advantages, it provides multi-channel programming, let us feel each of us have their own CPU and other resources, can improve the utilization of the computer. Many people do not understand, since the process is so good, why do threads? In fact, careful observation will find that the process is still a lot of defects, mainly reflected in two points:

      • A process can only do one thing at a time, and if you want to do two or more things at once, the process is powerless.
      • If a process is blocked during execution, such as waiting for input, the entire process hangs, even if some work in the process does not depend on the input data, it cannot be executed.

For example, we use QQ chat, QQ as an independent process if only one thing at the same time, how can he realize at the same moment to be able to monitor the keyboard input, but also can listen to other people send you the message, while still can send someone else's message on the screen? You would say that the operating system is not a tick? But my pro, tick refers to a different process between the time, that is, the operating system to handle your QQ task, and switch to the Word document task, each CPU time slice to your QQ program, your QQ or can only do one thing at the same time.

A bit more straightforward, an operating system like a factory, the factory has a lot of production workshops, different workshops to produce different products, each workshop is equivalent to a process, and your factory is poor, insufficient power, the same time only to a workshop power supply, in order to allow all the workshop can be produced simultaneously, Your factory electrician can only give different workshop time power supply, but your QQ workshop, found that only a working workers, the result is very low production efficiency, in order to solve this problem, should do? Yes, you must have thought of, is to add a few workers, let a few artificial people work in parallel, this every worker, is a thread!

2. Threads
    • A thread is the smallest unit that the operating system can perform operations on. It is included in the process and is the actual operating unit of the process.
    • A thread refers to a single sequential control flow in a process in which multiple threads can be concurrent and each thread performs different tasks in parallel.
    • The process must first create a thread to manipulate the CPU.
    • All threads in the same process share the same block of memory space.
2.1 Thread Call 2.1.1 Direct call
1 ImportThreading2 Import Time3 4 5 deffunc (n):6     Print("Task", N)7Time.sleep (2)8 9 Ten #execute with multithreading, print both Task 1 and Task 2, and then wait two seconds for the program to end.  OneT1 = Threading. Thread (Target=func, args= ("1",))#generate a thread instance AT2 = Threading. Thread (Target=func, args= ("2",)) -T1.start ()#Start Thread -T2.start ()
2.2.2 Inherited calls
1 ImportThreading2 Import Time3 4 5 classMyThread (Threading. Thread):6     def __init__(self, n):7Super (MyThread, self).__init__()8SELF.N =N9 Ten     defRun (self):#define the function to be run by each thread, where the function must be run One         Print("running my task", SELF.N) ATime.sleep (2) -  -  theT1 = MyThread ("1")#Instantiating Threads -T2 = MyThread ("2") -  -T1.start ()#Start Thread + T2.start () -  + Print("finished")

2.2 Join

The main thread does not execute until the child threads have finished executing. The main thread does not wait on a child thread if there is an action in the child thread that affects the speed of sleep.

No join
1 ImportThreading2 Import Time3 4 5 defRun (N):#performed by a child thread6     Print("Task", N, Threading.current_thread ())7Time.sleep (2)8     Print("finished", N, Threading.current_thread ())9 Ten  One  forIinchRange (50): At = Threading. Thread (Target=run, args=(i,)) - T.start () -  the Print("do not wait for the child thread to finish executing the main threads", Threading.current_thread (), Threading.active_count ())#will run the child thread first, print the task ... And then run the main thread, print "Do not wait for the thread to finish executing the main course", and finally continue to run the child thread, print finished ...
There is a join
1 ImportThreading2 Import Time3 4 5 defrun (n):6     Print("Task", N)7Time.sleep (2)8     Print("finished", N)9 Ten  OneStart_time =time.time () AThreads_obj = []#This list is used to hold the generated thread -  forIinchRange (50): -t = Threading. Thread (Target=run, args=(i,)) theT.start ()#T is a loop body variable that is not released after the loop ends.  -Threads_obj.append (t)#in order not to block the boot of the subsequent thread, do not join here, first put in a list.  -  - Print("wait for the child thread to finish executing ...") +  -  forTdinchThreads_obj:#loops The thread instance list, waiting for all threads to finish executing.  +Td.join ()#The join () function is that after all the child threads have finished executing, the main line friend continues execution.  A  at Print("wait for the child thread to finish executing the main line friend continue execution") - Print("total time-consuming", Time.time ()-start_time) - #Printing results: Print task first ...; Then print "Wait for the child thread to finish ..." and then print finished ...; Final print "Wait for thread friend to finish" and run time

2.3 Daemon Threads

The daemon thread serves the non-daemon thread, and the entire program exits after the non-daemon thread exits.

1 ImportThreading2 Import Time3 4 5 defrun (n):6     Print("Task", N)7Time.sleep (2)8     Print("finished", N)9 Ten  One  forIinchRange (50): At = Threading. Thread (Target=run, args=(i,)) -T.setdaemon (True)#the t thread is set to the daemon thread, which is the daemon thread for the main thread of the program, and the T thread exits when the main thread exits, and the other child threads initiated by T will exit at the same time, regardless of whether the task is completed or not - T.start () the  -  - Print("after the main thread executes, the program exits without waiting for the execution result of the daemon thread.")#do not print finished ...

2.4 Mutual Exclusion Lock (mutex)

A process can start multiple threads, multiple threads share the memory space of the parent process, which means that each thread can access the same data, at this time, if 2 threads simultaneously to modify the same data, what will happen?

In case of no mutex:
1 #-*-coding:utf-8-*-2 ImportThreading3 Import Time4 5Nums =06 7 8 defrun (n):9     GlobalNumsTenTime.sleep (2) OneNums + = 1 A  -  -Threads_obj = [] the  forIinchRange (1000): -t = Threading. Thread (Target=run, args=(i,)) - T.start () - threads_obj.append (t) +  -  forTinchThreads_obj: + T.join () A  at Print("Final nums:", Nums)

In Python2, it was found that the results of the operation were not expected 1000, but smaller than 1000, such as:

In Python3, it is found to be running normally (Python3 may automatically increase the lock to avoid this condition), such as:

Why does the result of each run be different? Ha, very simple, if you have a A, a, two threads, at this time to the NUM to reduce the 1 operation, because 2 threads are concurrently running concurrently, so 2 threads are likely to take the num=0 this initial variable to the CPU to calculate, when a thread to end the result is 1, But at this point the result of the B-thread operation is also 1, two threads at the same time the result of the CPU operation is assigned to the NUM variable, the result is 1. What about that? It is very simple that each thread will modify the data in order to avoid having to modify it when it is not finished, so you can add a lock to the data so that other threads will have to wait for you to modify the data and release the lock before accessing the data.

To add a mutex lock:
1 #-*-coding:utf-8-*-2 ImportThreading3 Import Time4 5 6 defrun (n):7     GlobalNums#each thread can get and modify the global variable8Time.sleep (1)9Lock.acquire ()#Get lockTenNums + = 1#operation operations on global variables OneLock.release ()#Release Lock A  -  -Nums = 0#Setting Global Variables theLock = Threading. Lock ()#generate a global lock -Threads_obj = [] -  forIinchRange (1000): -t = Threading. Thread (Target=run, args=(i,)) + T.start () - threads_obj.append (t) +  A  forTinchThreads_obj: at T.join () -  - Print("Final nums:", Nums)

After adding the thread lock, run the program under Python2 and Python3 respectively, the result is as follows:

3. The difference between a process and a thread
    • A thread is an instruction set that executes, and a process is a collection of resources.
    • The thread starts faster and the process starts slowly. But after running, there is no comparability.
    • Threads share memory space, and process memory is independent of each other.
    • The threads of the same process can communicate directly, and communication between processes must be implemented through an intermediary agent process.
    • Creating a new thread is as simple as creating a new process that requires a clone of its parent process.
    • A thread can control and manipulate other threads in the same process, but the process can only manipulate its child processes.
    • Modifying the main thread has the potential to affect the behavior of other threads, but modifications to the parent process do not affect the child process.

19-python-Processes and Threads

Related Article

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.