1.1th Way: Threading Module 1) Single thread execution
#-*-coding:utf-8-*-Import TimedefMain ():Print("I was wrong ... ") Time.sleep (1)if __name__=="__main__": Start_time=time.time () forIinchRange (5): Main () End_time=time.time ()Print("The run time is %s"% (End_time-start_time))
2) Multithreaded execution
- The main thread waits for all the child threads to end before they end
#-*-coding:utf-8-*- fromThreadingImportThreadImport Time#1. If multiple threads are executing the same function, they will not affect each other.defMain ():Print("I was wrong ... ") Time.sleep (1)if __name__=="__main__": Start_time=time.time () forIinchRange (5): #Process (target=test) processes complete multitaskingt = Thread (target=main) T.start () End_time=time.time ()Print("The run time is %s"% (End_time-start_time))
2. The difference between threads and processes
- A process is a resource-allocation unit, resource, memory, screen, etc.
- Thread is the unit of CPU dispatch
- 1 process has 1 main thread, the main thread can create multiple child threads
- The main thread task completes, waiting for the sub-thread's task to complete
3.2nd way: Thread Subclass creates threads
#Coding=utf-8ImportThreadingImport TimeclassMyThread (Threading. Thread):defRun (self): forIinchRange (3): Time.sleep (1) msg="I ' m"+self.name+' @ '+STR (i)#The Name property holds the names of the current thread. Print(msg)if __name__=='__main__': T=MyThread () T.start ( )
4. Zombie process, orphan process, process No. 1th, number No. 0
- Zombie Process: The child process ends, the parent process has not yet given it a corpse, at this time the child process becomes a zombie process
- Orphan process: The parent process ends prematurely, without waiting for the child process to end, at which time the child process becomes an orphan process
- Process Number No. 0 is responsible for switching tasks.
- Process 1th is responsible for generating, destroying other sub-processes
5. Order of execution of threads: unordered
- Execution Result: (The result of the operation may be different, but broadly consistent)
#Coding=utf-8ImportThreadingImport TimeclassMyThread (Threading. Thread):defRun (self): forIinchRange (3): Time.sleep (1) msg="I ' m"+self.name+' @ '+Str (i)Print(msg)defTest (): forIinchRange (5): T=MyThread () T.start ( )if __name__=='__main__':
- Python interpreter masks differences in underlying hardware
6. Summary
- Each thread must have a name, although the above example does not specify the name of the thread object, but Python automatically assigns a name to the thread.
- When the thread's run () method ends, the thread finishes.
- The thread scheduler cannot be controlled, but there are other ways to influence how threads are dispatched.
- Several states of a thread
6 Thread Threading