Processes and Threads
- Process: Memory independent, thread sharing memory of the same process
- A process is a collection of resources, a thread is an execution unit
- Processes cannot directly access each other, and processes in the same process can communicate with each other
- Create a new process consumes system resources, threads are very lightweight, saving only the necessary data when the thread is running, such as context, program stack information
- Threads in the same process can control each other, and the parent process can control the child process
1 ImportThreading2 Import Time3 4 defsayhi (num):5 Print('Num:', num)6Time.sleep (3)7 8A = Threading. Thread (target=sayhi,args= (1,))9b = Threading. Thread (target=sayhi,args= (2,))TenNow1 =time.time () One Print(NOW1) A A.start () - B.start () -Now2 =time.time () the Print(NOW2) - Print(Threading.active_count ()) - #includes main thread, total 3 - Print(A.getname ()) + Print(B.getname ()) - + classMyThread (Threading. Thread): A def __init__(self,n): atThreading. Thread.__init__(self) -SELF.N =N - - defRun (self): - Print('running on thread $s'%SELF.N) -Time.sleep (3) inNOW3 =time.time () - Print(NOW3) toT1 = MyThread (1) +T2 = MyThread (2) - T1.start () the T2.start () * Print(T1.getname ()) $ Print(T2.getname ())Panax NotoginsengNOW4 =time.time () - Print(NOW4) the +Thread_list = [] A forIinchRange (10): theS1 = Threading. Thread (target=sayhi,args=(i,)) + S1.start () - thread_list.append (S1) $NOW5 =time.time () $ Print(NOW5) - forRinchthread_list: -R.join ()#s1.wait () the Print('--work done--') -NOW6 =time.time ()Wuyi Print(NOW6) the Print('Primary'. Center (20,'-')) - Wu - forIiinchRange (10): AboutS2 = Threading. Thread (target=sayhi) $ S2.setdaemon (S2) -S2.start ()View Code
Python3 processes and Threads