1.1 Process
Consider a scenario: browser, NetEase cloud music and notepad++ three software can only be executed sequentially is what kind of scene? In addition, if there are two programs A and B, program A will need to read a large amount of data input (I/O operations) during the execution of the process, while the CPU can only wait silently until task a reads the data to continue execution, thus wasting CPU resources. Have you ever thought that while program a reads the data, let program B go, and when program a reads the data, let program B pause. Smart, of course it's okay, but here's a keyword: toggle.
Since it is switching, then this involves state saving, state recovery, plus program A and program B required system resources (memory, hard disk, keyboard, etc.) are not the same. There is a natural need to have something to record what the program A and program B need, how to identify program A and program B, etc. (such as reading).
Process definition:
A process is a dynamic execution of a program on a data set. The process is generally composed of three parts: program, data set and process control block. The program we write is used to describe what the process is going to accomplish and how it is done, and the data set is the resource that the program needs to use in its execution, and the process control block is used to document the external characteristics of the process, to describe the process of its execution, and it can be used to control and manage the process, which is the only sign of
One example illustrates the process:
Imagine a computer scientist with a good hand in cooking is baking a birthday cake for his daughter. He has recipes for birthday cakes, ingredients for the kitchen: flour, eggs, sugar, vanilla juice, etc. In this analogy, the recipe for making a cake is a program (that is, an algorithm that is described in the proper form), and the computer scientist is the processor (CPU), and the raw material that makes the cake is the input data. The process is the sum of a series of actions that the chef reads recipes, takes a variety of ingredients, and bakes cakes. Now suppose the son of a computer scientist came in crying and said his head was stung by a bee. Computer scientists record what he did to the recipe (save the current state of the process), and then take out a first aid manual and follow the instructions to treat the sting. Here, we see the processor switching from one process (making a cake) to another high-priority process (implementing medical treatment), each with its own program (recipes and First aid manuals). When the Bee sting was finished, the computer scientist came back to make the cake and went on from the step he left.
1.2 Threads
The occurrence of the thread is to reduce the consumption of the context switch, improve the concurrency of the system, and break through a process can only do the same thing, so that in-process concurrency becomes possible.
Suppose that a text program needs to accept keyboard input, display the content on the screen, and save the information to the hard drive. If there is only one process, it is bound to cause the same time only the embarrassment of doing the same thing (when saved, you can not enter content through the keyboard). If there are multiple processes, each process is responsible for a task, process A is responsible for receiving keyboard input tasks, and process B is responsible for displaying the content on the screen, and process C is responsible for saving the contents to the hard disk. The collaboration between the process a,b,c involves the process communication problem, and there is something that we all need to have ——-text content, constantly switching to cause loss of performance. If there is a mechanism, you can make the task A,b,c share resources, so that context switches need to save and restore less content, but also reduce the performance of the communication caused by the loss, it is good. Yes, this mechanism is a thread.
A thread is also called a lightweight process, which is a basic CPU execution unit and the smallest unit in a program's execution, consisting of a thread ID, a program counter, a register collection, and a stack. The introduction of threads reduces the overhead of program concurrency and improves the concurrency performance of the operating system. The thread does not have its own system resources.
1.3 Process-to-thread relationships
Process is a computer program on a set of data on a running activity, the system is the basic unit of resource allocation and scheduling, is the basis of the operating system structure. Or a process is a program with a certain set of independent functions on a data collection of a running activity, the process is the system for resource allocation and scheduling of an independent unit.
A thread is an entity of a process that is the basic unit of CPU dispatch and dispatch, which is a smaller unit that can run independently than a process.
Relationship of process and thread:
(1) A thread can belong to only one process, while a process may have multiple threads, but at least one thread.
(2) A resource is allocated to a process, and all the threads of the same process share all the resources of that process.
(3) The CPU is assigned to a thread, that is, a thread that actually runs on the CPU.
1.4 Parallel and concurrent
Parallel processing (Parallel processing) is a computational method that can perform two or more processes simultaneously in a computer system. Parallel processing can work on different aspects of the same program at the same time. The main purpose of parallel processing is to save time to solve large and complex problems. Concurrent processing (concurrency processing): Refers to a time period in which several programs are running to completion, and these programs are running on the same processor (CPU), but only one program at any point on the processing machine (CPU) runs
The key to concurrency is that you have the ability to handle multiple tasks, not necessarily at the same time. The key to parallelism is that you have the ability to handle multiple tasks at the same time. So, parallelism is a subset of concurrency
1.5 Synchronous vs. asynchronous
In the computer field, synchronization means that when a process executes a request, if the request takes a while to return the information, the process will wait until the return message is received until the process continues; async means that the processes do not have to wait all the time, but continue to do the following. Regardless of the status of other processes. The system notifies the process when a message is returned, which can improve the efficiency of execution. For example, the telephone is synchronous communication, the short interest is asynchronous communication.
Two threading Module 2.1 thread object creation 2.1.1 Thread class is created directly
Import Threadingimport timedef countnum (n): # defines a function for a thread to run print ("Running on number:%s"%n) Time.sleep (3) if __ name__ = = ' __main__ ': t1 = Threading. Thread (target=countnum,args= ()) #生成一个线程实例 t2 = Threading. Thread (target=countnum,args=,)) T1.start () #启动线程 t2.start () print ("ending!")
2.1.2 Thread class-inheriting creation
#继承Thread式创建import threadingimport timeclass MyThread (threading. Thread): def __init__ (self,num): Threading. Thread.__init__ (self) self.num=num def run (self): print ("Running on number:%s"%self.num) Time.sleep (3) t1=mythread (T2=mythread) T1.start () T2.start () print ("Ending")
2.2 Instance methods of the thread class 2.2.1 join () and Setdaemon ()
# join (): The parent thread of this child thread will remain blocked until the child thread finishes running. # Setdaemon (True): ' The thread is declared as a daemon thread and must be set before the start () method call, and if not set to the daemon, it will be indefinitely suspended. When we are running the program, executing a main thread, if the main thread creates a sub-thread, the main thread and the child thread are suited two ways, running separately, then when the main thread finishes trying to exit, it verifies that the child thread is complete. If the child thread is not completed, the main thread waits for the child thread to complete before exiting. But sometimes what we need is that as long as the main thread is complete, regardless of whether the child thread is complete, and the main thread to exit, then you can use the Setdaemon method "" "Import threadingfrom time import Ctime,sleepimport Timedef Music (name): Print ("Begin listening to {name}". {time} '. Format (Name=name,time=ctime ())) sleep (3) print ("End Listening {time}". Format (Time=ctime ())) def Blog ( Title): Print ("Begin recording the {title}". {time} '. Format (Title=title,time=ctime ())) sleep (5) print (' End recording {time} '. Format (Time=ctime ())) threads = []T1 = Threading. Thread (target=music,args= (' FILL ME ',)) t2 = Threading. Thread (target=blog,args= (",)) threads.append (T1) threads.append (t2) If __name__ = = ' __main__ ': #t2. Setdaemon (True) fo R T in Threads: #t. Setdaemon (True) #注意: Be sure to set T.start before start () #t. Join () #t1. Join () #t2. Join () # Consider the results under these three join locations? Print ("All over%s"%ctime ())
Daemon2.2.2 Other methods
Methods for thread instance objects
# isAlive (): Returns whether the thread is active. # getName (): Returns the thread name. # SetName (): Sets the thread name. Some of the methods provided by the threading module are: # threading.currentthread (): Returns the current thread variable. # threading.enumerate (): Returns a list that contains the running thread. Running refers to threads that do not include pre-and post-termination threads until after the thread has started and ends. # Threading.activecount (): Returns the number of running threads with the same result as Len (Threading.enumerate ()).
Ps:http://www.cnblogs.com/yuanchenqi/articles/6755717.html (refer to Teacher's blog)
Day 36 (07/17) process and thread