python高效编程技巧12(如何实现线程之间的通信)
来源:互联网 发布:数据库原理与应用第2版 编辑:程序博客网 时间:2024/06/09 14:48
# 进行线程之间的通信的原理:一个进程内的多个线程,使用的是同一个虚拟地址空间,使用标准库中的Queue.Queue,它是一个线程安全的队列,io线程把数据放入队列,cpu线程从队列中提取数据
#!/usr/bin/env python# -*- coding:utf-8 -*-# 进行线程之间的通信的原理:一个进程内的多个线程,使用的是同一个虚拟地址空间from threading import Thread# 创建一个队列来实现线程之间的通信,但是这是线程不安全的,调用的时候需要使用lock# 而Queue是线程安全的队列,调用时不用处理from Queue import Queue# io线程class ioThread(Thread): def __init__(self, queue): # 要调用分类的构造器 Thread.__init__(self) self.queue = queue def run(self): # io线程创建数据 self.queue.put((1, 2)) print "执行了io操作"# cpu线程class cpuThread(Thread): def __init__(self, queue): # 要调用分类的构造器 Thread.__init__(self) self.queue = queue def run(self): while True: # 从队列中取数据 print "========" first, second = self.queue.get() print first, second print "执行了cpu密集型操作"# ===========类似生产者和消费者模式==============q = Queue()ios = [ioThread(q) for i in xrange(1, 11)]for io in ios: io.start()cpu = cpuThread(q)cpu.start()
阅读全文
0 0
- python高效编程技巧12(如何实现线程之间的通信)
- python高效编程技巧13(如何在线程之间实现事件通知)
- python高效编程技巧14(如何使用线程池)
- python高效编程技巧6(如何实现用户的历史记录功能)
- python高效编程技巧8(如何实现可迭代对象和迭代器对象)
- python高效编程技巧9(如何读写csv文件)
- python高效编程技巧10(如何读写json)
- python高效编程技巧11(如何使用多线程)
- python高效编程技巧3(如何统计序列中元素出现的频率)
- Python高效编程技巧
- Python高效编程技巧
- Python高效编程技巧
- Python高效编程技巧
- Python高效编程技巧
- Python高效编程技巧
- Python高效编程技巧
- Python高效编程技巧
- Python高效编程技巧
- POJ 2601|URAL 1047|Simple Caluculations|数学推导
- Django 一张网站框架图
- 小故事有大能量(爱情故事)
- 常用的Python os模块
- 拓展欧几里得
- python高效编程技巧12(如何实现线程之间的通信)
- Retrofit2 完全解析 探索与okhttp之间的关系
- Spring Cloud构建微服务架构:服务注册与发现(Eureka、Consul)【Dalston版】
- MyEclipse中配置struts.xml自动提示的方法
- bzoj 2763: [JLOI2011]飞行路线
- css属性的备忘录
- Excle快速生成SQL公式
- 九九乘法表
- spring-mvc01