Python多线程编程使用Queue模块保持线程同步
来源:互联网 发布:幻城网络剧原声带 编辑:程序博客网 时间:2024/05/17 00:00
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import
threading
# 导入threading模块
import
Queue
# 导入Queue模块
class
Producer(threading.Thread):
# 定义生产者类
def
__init__(
self
,threadname):
threading.Thread.__init__(
self
,name
=
threadname)
def
run(
self
):
global
queue
# 声明queue为全局变量
queue.put(
self
.getName())
# 调用put方法将线程名添加到队列中
print
self
.getName(),
'put '
,
self
.getName(),
' to queue'
class
Consumer(threading.Thread):
# 定义消费者类
def
__init__(
self
,threadname):
threading.Thread.__init__(
self
,name
=
threadname)
def
run(
self
):
global
queue
print
self
.getName(),
'get '
,queue.get(),
'from queue'
#调用get方法获取队列中内容
queue
=
Queue.Queue()
# 生成队列对象
plist
=
[]
# 生成者对象列表
clist
=
[]
# 消费者对象列表
for
i
in
range
(
10
):
p
=
Producer(
'Producer'
+
str
(i))
plist.append(p)
# 添加到生产者对象列表
for
i
in
range
(
10
):
c
=
Consumer(
'Consumer'
+
str
(i))
clist.append(c)
# 添加到消费者对象列表
for
i
in
plist:
i.start()
# 运行生产者线程
i.join()
for
i
in
clist:
i.start()
# 运行消费者线程
i.join()
######运行结果######
>>> Producer0 put Producer0 to queue
Producer1 put Producer1 to queue
Producer2 put Producer2 to queue
Producer3 put Producer3 to queue
Producer4 put Producer4 to queue
Producer5 put Producer5 to queue
Producer6 put Producer6 to queue
Producer7 put Producer7 to queue
Producer8 put Producer8 to queue
Producer9 put Producer9 to queue
Consumer0 get Producer0
from
queue
Consumer1 get Producer1
from
queue
Consumer2 get Producer2
from
queue
Consumer3 get Producer3
from
queue
Consumer4 get Producer4
from
queue
Consumer5 get Producer5
from
queue
Consumer6 get Producer6
from
queue
Consumer7 get Producer7
from
queue
Consumer8 get Producer8
from
queue
Consumer9 get Producer9
from
queue
0 0
- Python多线程编程使用Queue模块保持线程同步
- python多线程编程: 使用互斥锁同步线程
- python多线程编程: 使用互斥锁同步线程
- python多线程编程: 使用互斥锁同步线程
- python多线程编程: 使用互斥锁同步线程
- python多线程编程: 使用互斥锁同步线程
- Python使用条件变量保持线程同步
- python多线程编程(3): 使用互斥锁同步线程
- python多线程编程(3): 使用互斥锁同步线程
- python多线程编程(3): 使用互斥锁同步线程
- python多线程编程(3): 使用互斥锁同步线程
- python多线程编程(3): 使用互斥锁同步线程
- 代码笔记 | 多线程使用queue模块同步访问共享数据
- Learning Python(16)--多线程编程(threading,Queue模块)
- Python多线程使用及线程同步
- Python:使用threading模块实现多线程编程七[使用Condition实现复杂同步]
- Python:使用threading模块实现多线程编程七[使用Condition实现复杂同步]
- 多线程编程(3): 使用互斥锁同步线程
- 工作零散记忆_007
- windows server 修改TCP参数
- Oracle与MySQL的几点区别(供自己学习学习)
- 模块管理常规功能自定义系统的设计与实现(36--终级阶段 综合查询[3])
- LINUX UMASK详解
- Python多线程编程使用Queue模块保持线程同步
- 分行模块,自动识别英文和型号数[推荐精华]
- phpize报cannot find autoconf
- 服务器流量异常的解决方案
- android__9.png图片
- 大批量数据更新,分享给大家。
- 谈谈Runtime类中的freeMemory,totalMemory,maxMemory等几个方法
- codeforces 7D Palindrome Degree 字符串hash
- 《大话设计模式》—— 读后感 (12)牛市股票还会亏钱?—— 外观模式