Python: thread, python thread
Thread
1. threads and processes
Process: The program in progress. A process can process a task. For a person, a person is a process. A process contains threads.
Thread: Lightweight Process. Only one thing can be done at a time point. One person can do multiple things, each of which is a thread.
2. The thread is the minimum unit of CPU scheduling. Process is the minimum unit for resource allocation.
3. The time-space overhead of enabling a thread is lower than that of enabling a process, and the cpu switching between threads is faster than switching between processes.
4. A program can contain multiple processes and threads at the same time.
1) Call the module to enable the thread
Import osimport timefrom threading import Threaddef func (): # subthread time. sleep (1) print ('Hello world', OS. getpid () thread_lst = [] for I in range (10): t = Thread (target = func) t. start () thread_lst.append (t) [t. join () for t in thread_lst] print (OS. getpid () # main thread
2) Enable the thread of the call class
Import osimport timefrom threading import Threadclass MyThread (Thread): count = 0 # static attribute def _ init _ (self, arg1, arg2): super (). _ init _ () self. arg1 = arg1 self. arg2 = arg2 def run (self): MyThread. count + = 1 time. sleep (1) print ('% s, % s' % (self. arg1, self. arg2, self. name, OS. getpid () for I in range (10): t = MyThread (I, I * ') t. start () print (t. count)