python中的threading模块
来源:互联网 发布:网络共享打印机脱机 编辑:程序博客网 时间:2024/05/20 03:07
转载自http://blog.chinaunix.net/uid-27571599-id-3484048.html
threading提供了一个比thread模块更高层的API来提供线程的并发性。这些线程并发运行并共享内存。
下面来看threading模块的具体用法:
一、Thread的使用 目标函数可以实例化一个Thread对象,每个Thread对象代表着一个线程,可以通过start()方法,开始运行。
这里对使用多线程并发,和不适用多线程并发做了一个比较:
首先是不使用多线程的操作:
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/python
#compare for multi threads
import
time
def
worker():
print
"worker"
time.sleep(
1
)
return
if
__name__
=
=
"__main__"
:
for
i
in
xrange
(
5
):
worker()
执行结果如下:
下面是使用多线程并发的操作:
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/python
import
threading
import
time
def
worker():
print
"worker"
time.sleep(
1
)
return
for
i
in
xrange
(
5
):
t
=
threading.Thread(target
=
worker)
t.start()
可以明显看出使用了多线程并发的操作,花费时间要短的很多。
二、threading.activeCount()的使用,此方法返回当前进程中线程的个数。返回的个数中包含主线程。
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/usr/bin/python
#current's number of threads
import
threading
import
time
def
worker():
print
"test"
time.sleep(
1
)
for
i
in
xrange
(
5
):
t
=
threading.Thread(target
=
worker)
t.start()
print
"current has %d threads"
%
(threading.activeCount()
-
1
)
三、threading.enumerate()的使用。此方法返回当前运行中的Thread对象列表。
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/python
#test the variable threading.enumerate()
import
threading
import
time
def
worker():
print
"test"
time.sleep(
2
)
threads
=
[]
for
i
in
xrange
(
5
):
t
=
threading.Thread(target
=
worker)
threads.append(t)
t.start()
for
item
in
threading.
enumerate
():
print
item
print
for
item
in
threads:
print
item
四、threading.setDaemon()的使用。设置后台进程。
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/python
#create a daemon
import
threading
import
time
def
worker():
time.sleep(
3
)
print
"worker"
t
=
threading.Thread(target
=
worker)
t.setDaemon(
True
)
t.start()
print
"haha"
可以看出worker()方法中的打印操作并没有显示出来,说明已经成为后台进程。
0 0
- python中的threading模块
- python中的线程使用--threading模块
- python模块学习(threading模块中的Thread类)
- python模块学习(threading模块中的Timer类)
- python模块学习(threading模块中的Condition类)
- python模块学习(threading模块中的Event类)
- python模块学习(threading模块中的Barrier类)
- Python threading模块
- Python threading模块简介
- python threading模块
- Python 多线程 Threading模块
- Python的threading模块
- PYTHON THREADING模块
- python threading多线程模块
- python多线程-threading模块
- Python标准模块--threading
- Python threading模块初探
- Python标准模块--threading
- 【伯乐在线】FACEBOOK产品设计总监:设计APP时的14个必考题
- JS实现验证码
- [初学hadoop]错误信息:hdfs://192.168.0.16:9000/report.bak, expected: file:///
- js escape()方法解析
- 怎么将PPT中的图文完好的转换成PDF
- python中的threading模块
- Reactor Proactor 两个IO多路复用的方法
- debian(wheezy)gnome-keyring:: couldn't connect to: /home/username/.cache/keyring-XXXXXX/pkcs11
- MySQL 的唯一索引
- SpringMVC+Spring3+Hibernate Quartz定时任务调用service查询获取不到CurrentSession
- IOS APPstore发布
- 十个最火的HTML5框架与移动应用框架的比较
- 重载函数的重载确定过程
- BZOJ 2342 [Shoi2011] 双倍回文 Manacher + set维护