9.9 Theory Thread
1. What is the thread thread refers to an assembly line process work
The process is simply not an execution unit, the process is actually a resource unit, a native threads within a process, thread execution unit is
2, the process VS thread
-
They threads within the same process share resources within the process, thread resources within the different processes must be isolated
-
Creating threads is less expensive to process than create more
9.91 in two ways open thread
method one:
from multiprocessing Import Process from Threading Import the Thread Import Time DEF Task (name): Print ( ' % S running IS ' % name) the time.sleep ( . 3) # end of the main thread running to wait for the end of the sub-thread, as further sub-thread to use the resources of the main thread IF the __name__ == ' __main__ ' : T = the thread (target = Task, args = ( ' Egon ' ,)) # T = Process (target = Task, args = ( 'Egon',)) t.start () Print ( " Main thread " ) # Egon main thread running IS
Second way:
from multiprocessing import Process from threading import Thread import time class MyThread(Thread): def run(self): print('%s is running' %self.name) time.sleep(3) if __name__ == '__main__': t=MyThread() t.start() print('主线程')#Thread-1 is running the main thread
9.92 difference between processes and threads
1、PID:
from threading import Thread import time,os def task(): print('%s is running' %os.getpid())#11352 is running time.sleep(3) if __name__ == '__main__': t=Thread(target=task,) t.start() print('主线程',os.getpid())#主线程 11352
2, thread creation overhead small
3, multiple threads share resources within the process in the same process
from threading import Thread import time,os x=1000 def task(): global x x=0 if __name__ == '__main__': t=Thread(target=task,) t.start() t.join() print('主线程',x) #主线程 0
Other methods 9.93 thread object
-
is_alive (): Returns the thread is active
-
getName (): Returns the thread name
-
setName (): Set the thread name
-
enumerate (): Returns a list of running threads. Refers to the thread starts running, before the end, it does not include a thread before starting and after termination.
-
active_count (): Returns the number of running threads, and len (threading.enumerate ()) have the same result.
-
current_thread (): Returns the current thread variable
from threading import Thread,current_thread,active_count,enumerate import time,os def task(): print('%s is running' %current_thread().name) time.sleep(3) if __name__ == '__main__': t1=Thread(target=task,name='第一个线程')#第一个线程 is running t2=Thread(target=task,)#Thread-1 is running t3=Thread(target=task,)#Thread-2 is running t1.start() t2.start() t3.start() print(t1.is_alive())#True print(active_count())#4 print(enumerate())#[<_MainThread(MainThread, started 13004)>, <Thread(第一个线程, started 14044)>, <Thread(Thread-1, started 11380)>, <Thread(Thread-2, started 9452)>] print('主线程',current_thread().name)#主线程 MainThread