补充:守护进程
守护进程例子:
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(‘====>‘)
守护进程应用:
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() #一旦结束就意味着消费者取完东西了 44 45 print(‘主进程结束‘)
线程:
1、什么是线程?
线程指的是一条流水线的工作过程;
进程根本就不是一个执行单位,进程其实是一个资源单位;
一个进程自带一个线程,线程才是执行单位;
2、线程 VS 进程
1、同一线程内的线程们共享该进程内的资源,不同进程内的线程资源肯定是隔离的;
2、创建线程的开销比进程要小的多;
开启线程的两种方式:
方式一:
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(‘===主线程‘)
方式二:推荐用自己继承的Thread,self.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(‘主线程...‘)
进程 VS 线程:
1 from threading import Thread 2 import time,os 3 4 def task(): 5 print(‘%s is running ‘ %os.getpid()) 6 time.sleep(1) 7 if __name__ == ‘__main__‘: 8 t = Thread(target=task,) 9 t2 = Thread(target=task,) 10 t.start() 11 t2.start() 12 print(‘===>主线程:%s‘ %os.getpid())
2、线程创建开销小
3、同一进程的多个线程共享该进程内的资源
1 from threading import Thread 2 import time,os 3 4 x = 1000 5 def task(): 6 global x 7 x= 0 8 9 if __name__ == ‘__main__‘: 10 t = Thread(target=task,) 11 t.start() 12 t.join() 13 print(‘主线程‘,x)
线程的其他方法:current_thread,active_count,enumerate
1 from threading import Thread,active_count,current_thread,enumerate 2 3 import time 4 5 def task(): 6 print(‘%s is running‘ %current_thread().name) #查看选择的线程名字 7 time.sleep(1) 8 9 if __name__ == ‘__main__‘: 10 t1 = Thread(target=task,name=‘第一个线程!‘) 11 t2 = Thread(target=task) 12 t3 = Thread(target=task) 13 t1.start() 14 t2.start() 15 t3.start() 16 print(t1.is_alive()) 17 print(active_count()) #查看线程数量 18 print(enumerate()) #把线程信息弄成一个列表 19 print(‘主线程%s‘ %current_thread().name)
守护线程:
原文地址:https://www.cnblogs.com/kermitjam/p/8954487.html
时间: 2024-11-07 21:36:46