进程间的通信
1.进程间的通信
""" 队列:先进先出 堆栈:先进后出 """ from mulitprocessing import Queue q = Queue(5) # 括号内可以传参数 表示的是这个队列的最大存储数 q.put(1) q.put(2) print(q.full()) # 判断队列是否满了 q.put(3) q.put(4) q.put(5) print(q.full()) q.put(6) # 当队列满了之后 再放入数据 不会报错 会原地等待 直到队列中有数据被取走(阻塞态) print(q.get()) print(q.get()) print(q.empty()) # 判断队列是否为空 print(q.get()) print(q.get()) print(q.get()) print(q.empty()) print(q.get_nowait()) # 取值 没有值不等待直接报错 print(q.get()) # 当队列中的数据被取完之后,再次获取,程序会阻塞,直到有人往队列里放入值 """ full get_nowait empty 都不适用于多进程的情况 """
进程间通信IPC机制
from multiprocessing import Process,Queue def producer(q): q.put('hello baby') def consumer(q): print(q.get()) if __name__ == '__main__': q = Queue() p = Process(target=producer,args=(q,)) c = Process(target=consumer,args=(q,)) p.start() c.start() """ 子进程放数据 主进程获取数据 两个子进程相互放 取数据 """
生产者消费者模型
from multiprocessing import Process,JoinableQueue import time import random def producer(name,food,q): for i in range(10): data = '%s生产的%s%s'%(name,food,i) time.sleep(random.random()) print(data) q.put(data) def consumer(name,q): while True: data = q.get() print('\033[31m%s吃了%s\033[0m'%(name,data)) time.sleep(random.random()) q.task_done() # 告诉队列你已经从队列中取出一个数据 并且处理完毕了 if __name__ == '__main__': q = JoinableQueue() p1 = Process(target=producer,args=('zmm','鱼',q)) p2 = Process(target=producer,args=('yzy','肉',q)) c1 = Process(target=consumer,args=('czh',q)) c2 = Process(target=consumer,args=('lc',q)) c1.daemon = True c2.daemon = True p1.start() p2.start() c1.start() c2.start() p1.join() p2.join() q.join() # 等到队列中数据全部取出
线程
什么是线程
进程线程其实都是虚拟单位,都是用来帮助我们形象的描述某种事物
进程:资源单位
线程:执行单位
将内存比作工厂,那么进程就相当于工厂里的车间,线程就相当于车间里的流水线
ps: 每个进程都自带一个线程,线程才是真正的执行单位,进程只是在线程运行过程中提供代码运行所需要的资源
为什么要有线程
开进程
1.申请内存空间 耗资源
2."拷贝代码" 耗资源
开线程
一个进程内可以起多个线程,并且线程与线程之间数据是共享的
ps:开启线程的开销要远远小于开启进程的开销
创建线程的两种方式
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import time from threading import Thread def task(name): print('\033[32m%s is running\033[0m'%name) time.sleep(1) print('%s is over'%name) # 开线程不需要在__main__代码块内 但是习惯性的还是写在__main__代码块内 t = Thread(target=task,args=('zmm',)) t.start() # 告诉操作系统开辟一个线程 线程的开销远远小于进程 # 小的代码执行完 线程就已经开启了 print('主')
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from threading import Thread import time class MyThread(Thread): def __init__(self,name): super().__init__() self.name = name def run(self): print('%s is running'%self.name) time.sleep(1) print('%s is over'%self.name) t = MyThread('zmm') t.start() print('主')
内存数据的共享问题
from threading import Thread money = 666 def task(): global money money = 100 t = Thread(target=task) t.start() print(money) # 100
守护线程
from threading import Thread,current_thread import time def task(i) print(current_thread().name) time.sleep(1) print('GG') t1 = Thread(target=task,args=(1,)) t2 = Thread(target=task,args=(2,)) t3 = Thread(target=task,args=(3,)) # t1.daemon = True # t2.daemon = True t3.daemon = True t1.start() t2.start() t3.start() print('zhu') """ Thread-1 Thread-2 Thread-3 zhu GG GG """ """ 主线程的结束也就意味着进程的结束 主线程必须等待其他非守护线程的结束才能结束 (意味着线程在运行的时候需要使用进程中的资源,而主线程一旦结束了,资源也就销毁了) """
线程对象及其他方法
from threading import Thread,current_thread,active_count import time import os def task(name,i) print('%s is running'%name) print('子current_thread:',current_thread().name) print('子',os.getpid()) time.sleep(i) print('%s is over'%name) t1 = Thread(target=task,args=('zmm',1)) t2 = Thread(target=task,args=('yzy',2)) t1.start() t2.start() ti.join() print('当前正在活跃的线程数:',active_count()) print('主') print('主',os.getpid()) print('主current_thread:',current_thread().name)
互斥锁
from threading import Thread,Lock import time n = 100 def task(mutex): global n mutex.acquire() num = n time.sleep(0.1) n = num - 1 mutex.release() t_list = [] mutex = Lock() for i in range(100): t = Thread(target=task,args=(mutex,)) t.start() t_list.append(t) for t in t_list: t.join() print(n)
小例子
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from threading import Thread import time def foo(): print(123) time.sleep(1) print("end123") def bar(): print(456) time.sleep(3) print("end456") if __name__ == '__main__': t1=Thread(target=foo) t2=Thread(target=bar) t1.daemon=True t1.start() t2.start() print("main-------") """ 123 456 main------- end123 end456 """