Python Basics-Processes, threads

Source: Internet
Author: User

Processes and Threads

What is a 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!

What is a thread

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 concurrently, each thread performing different tasks in parallel

The difference between a process and a thread

(1) A process is a separate unit of resource allocation and scheduling, while a thread is the basic unit of CPU scheduling (2) The same process can include multiple threads, and the thread shares the resources (registers, stacks, contexts) of the entire process, and a process includes at least one thread. (3) The creation of the process calls fork or vfork, while the thread's creation calls Pthread_create, and all the threads it owns after the process is finished are destroyed, and the end of the thread does not affect the end of other threads in the same process (4) The thread is a lightweight process, It takes much less time to create and destroy than a process, and all the execution functions in the operating system are created threads to complete (5) threads are generally synchronized and mutually exclusive when executed, because they share all the resources of the same process (6) threads have their own private properties TCB, thread ID, deposit Hardware context, and the process has its own private property process Control block PCB, these private properties are not shared, used to mark a process or a thread's flag Python threading module thread has 2 ways to call, as follows: Call directly
ImportThreadingImport TimedefSayhi (num):#define the functions to be run by each thread    Print("running on number:%s"%num) time.sleep (3)if __name__=='__main__': T1= Threading. Thread (Target=sayhi, args= (1,))#generate a thread instanceT2 = Threading. Thread (Target=sayhi, args= (2,))#generate another thread instanceT1.start ()#Start ThreadT2.start ()#start another thread    Print(T1.getname ())#Get thread name    Print(T2.getname ())

An inherited invocation

ImportThreadingImport TimeclassMyThread (Threading. Thread):def __init__(self, num): Threading. Thread.__init__(self) self.num=NumdefRun (self):#define the functions to be run by each thread        Print("running on number:%s"%self.num) Time.sleep (3)if __name__=='__main__': T1= MyThread (1) T2= MyThread (2) T1.start () T2.start ()Print(T1.getname ())#Get thread name    Print(T2.getname ())

Here is a way to handle multithreading: (Need to understand):

ImportThreadingImport Timedefrun (n):Print("Task:", N) time.sleep (2)    Print("Task done:", N) start_time=time.time () forIinchRange (10): T= Threading. Thread (target=run,args=(i,)) T.start ()Print("Cost :", Time.time ()-start_time)

The results of the operation are as follows:

is because the program itself is a main thread, the main thread and a child thread, then the child thread and the main thread has no problem, the equivalent of the child thread and the main thread is parallel. This explains why the main thread continues to go down after the child thread has been started by my main thread, without waiting for the child threads to finish executing.

But now there is a problem, we need to calculate the execution time of the thread, and let all the threads run before running the main program

Here you need to use a method of line thread join () meaning is actually waiting for the meaning of the code is as follows:

ImportThreadingImport Timedefrun (n):Print("Task:", N) time.sleep (2)    Print("Task done:", N) start_time=time.time () t_obj= []#Save Thread Instance forIinchRange (10): T= Threading. Thread (target=run,args=(i,)) T.start () t_obj.append (t)#in order not to block the boot of the subsequent thread, do not join here, first put in a list forIinchT_obj:#loop Thread instance list, waiting for all threads to finish executingI.join ()Print("All thread was done")Print("Cost :", Time.time ()-start_time)

Without join, the main thread will not wait for the child thread to finish and then go down, the main thread and the child thread execution is completely parallel, there is no dependency, you execute, I also execute. However, you will find that when you finally exit, the main thread will still wait for all the child threads to execute before exiting the program. Although you do not have to go down after the execution, but before the program exits, there will be a default join

But when the join is added, the main thread relies on the child threads to execute, then goes down, this is the role of join.

About Daemon Threads

If the thread is set as the daemon thread, the main program will not finish the pipeline, and it will end when the main program finishes executing.

The code example is as follows:

ImportThreadingImport Timedefrun (n):Print("Task:", N) time.sleep (2)    Print("Task done:", N) start_time=time.time () forIinchRange (10): T= Threading. Thread (target=run,args=(i,)) T.setdaemon (True)#set the current thread as the daemon threadT.start ()Print("All thread was done", Threading.current_thread (), Threading.active_count ())Print("Cost :", Time.time ()-start_time)

Python Basics-Processes, threads

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.