First, background knowledge
Theoretical basis
1. The role of the operating system:
(1) Hide ugly Complex hardware interface, provide good abstraction interface
(2) Management, scheduling process, and multiple processes to the hardware of the competition to become orderly
2. Multi-Channel technology:
(1) Background: For the single core, to achieve concurrency (now the host is generally multicore, name each core will use multi-channel technology, but the core and the core is not using multi-channel technology switch So, a program IO blocking, will wait until the end of the IO and re-Dispatch)
(2) Time multiplexing (multiplexing of a CPU's time slices) + space multiplexing (e.g. in-memory multi-channel programs)
Ii. process
1. What is a process
Process: a process in progress or a task, while the CPU is responsible for performing the task
2. The difference between process and procedure
A program is just a bunch of code, and a process refers to the process of running a program.
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.
In this analogy:
the recipe for making a cake is a program . (i.e. an algorithm that is described in the appropriate form)
The computer scientist is the processor (CPU)
and the ingredients for making cakes are 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 .
Need to emphasize is: the same program executes two times, that is also two processes, such as Open Storm video, although all are the same software, but one can play Cang Jing empty, one can play Rice Island love.
Third, thread
The appearance of the thread is to reduce the consumption of context switches, improve the system and discover, and break through a process can only do the same thing the flaw, make in-process concurrency 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.
4. 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 the process is a certain independent function of a program on a data set on a running activity, process is a system process 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
5. Parallelism and concurrency
Parallel processing is a computational method that can perform two or more processes simultaneously in a computer system. Parallel processing can work at the same time in the non-application of the same program, the main purpose of parallel processing is to save large and complex problem resolution time.
Concurrent processing: Refers to a period of time a few programs are in the start run to run, and these programs are running on the same processor (CPU), but at any point in time only one program on the processing Machine (CPU) run
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
6. Synchronous and asynchronous
Synchronous execution: When a program executes a task, another program must wait for it to complete before it can continue execution
Asynchronous execution: When a process performs a task, another process can continue without waiting for it to execute, and when a message returns, the system notifies the latter for processing, which can improve execution efficiency
For example, the call is synchronous communication, texting is asynchronous communication
Four, threading module
1. Creation of Thread objects
(1) thread class directly created
ImportThreadingImport TimedefCountnum (n):#define a function that a thread will run Print("running on number:%s"%N) time.sleep (3)if __name__=='__main__': T1= Threading. Thread (target=countnum,args= (23,))#generate a thread instanceT2 = Threading. Thread (target=countnum,args= (34,)) T1.start ()#Start ThreadT2.start ()Print("ending!")
(2) Tread-Class inheritance creation
#inherit thread-style creationImportThreadingImport TimeclassMyThread (Threading. Thread):def __init__(self,num): Threading. Thread.__init__(self) self.num=NumdefRun (self):Print("running on number:%s"%self.num) Time.sleep (3) T1=mythread (56) T2=mythread (78) T1.start () T2.start ()Print("ending")
Example Methods for 2.Thread classes
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, if it is not set to a 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" "When daemon is set to true, if the main thread exits, the child threads will also exit, and the child threads will continue to run until they exit normally. ImportThreading fromTimeImportCtime,sleepImport TimedefMusic (name):Print("Begin listening to {name}. {Time}". Format (name=name,time=CTime ())) Sleep (3) Print("end Listening {time}". Format (time=CTime ()))defBlog (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) forTinchThreads:#T.setdaemon (True) #注意: Must be set before startT.start ()#T.join () #T1.join () #T2.join () # Consider the results of these three join positions? Print("All over %s"%ctime ())
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 ()).
Python process thread