Added: Daemon
Daemon example:
from multiprocessing import Process import time def foo(): print(123) time.sleep(1) print('end123') def bar(): print(456) time.sleep(3) print('end456') if __name__ == '__main__': p1 = Process(target=foo) p2 = Process(target=bar) p2.daemon = True p1.start() p2.start() print('====>')
Daemon application:
1 import time 2 import random 3 from multiprocessing import Process,JoinableQueue 4 5 def consumer(name,q): 6 while True: 7 res = q.get() 8 time.sleep(random.randint(1,3)) 9 print('%s 吃了%s' %(name,res)) 10 q.task_done() 11 12 def producer(name,q,food): 13 for i in range(5): 14 time.sleep(random.randint(1,3)) 15 res = '%s%s' %(i,food) 16 q.put(res) 17 print('%s生产了%s' %(name,res)) 18 19 if __name__ == '__main__': 20 q = JoinableQueue() 21 22 p1 = Process(target=producer,args=('kermit1',q,'bianbian1')) 23 p2 = Process(target=producer,args=('kermit2',q,'bianbian2')) 24 p3 = Process(target=producer,args=('kermit3',q,'bianbian3')) 25 26 c1 = Process(target=consumer,args=('田秩玮1',q)) 27 c2 = Process(target=consumer,args=('田秩玮2',q)) 28 29 c1.daemon = True 30 c2.daemon = True 31 32 p1.start() 33 p2.start() 34 p3.start() 35 c1.start() 36 c2.start() 37 38 39 p1.join() 40 p2.join() 41 p3.join() 42 43 q.join( ) #Once it ends, it means that the consumer has finished fetching things 44 45 print ( ' The main process ends ' )
Thread:
1. What is a thread?
Thread refers to the working process of a pipeline;
A process is not an execution unit at all, a process is actually a resource unit;
A process has its own thread, and the thread is the execution unit;
2. Thread VS Process
1. Threads in the same thread share resources in the process, and thread resources in different processes must be isolated;
2. The overhead of creating threads is much smaller than that of processes;
There are two ways to start a thread:
method one:
1 from threading import Thread 2 import time 3 def task(name): 4 print('%s' %name) 5 time.sleep(1) 6 7 if __name__ == '__main__': 8 t = Thread(target=task,args=('kermit',)) 9 t.start() 10 print('===主线程')
Method 2: It is recommended to use your own inherited Thread, self.name will bring its own name
1 class MyThread(Thread): 2 def run(self): 3 print('%s is running...' %self.name) 4 time.sleep(1) 5 6 if __name__ == '__main__': 7 t = MyThread() 8 t.start() 9 print('主线程...')
Daemon thread: