您的位置:首页 > 编程语言 > Python开发

Python threading模块简介

2012-12-03 22:40 459 查看
python是支持多线程的,并且是native的线程。主要是通过thread和threading这两个模块来实现的。thread是比较底层的模 块,threading是对thread做了一些包装的,可以更加方便的被使用。这里需要提一下的是python对线程的支持还不够完善,不能利用多 CPU,但是下个版本的python中已经考虑改进这点,让我们拭目以待吧。

threading模块里面主要是对一些线程的操作对象化了,创建了叫Thread的class。一般来说,使用线程有两种模式,一种是创建线程要执行的 函数,把这个函数传递进Thread对象里,让它来执行;另一种是直接从Thread继承,创建一个新的class,把线程执行的代码放到这个新的 class里。我们来看看这两种做法吧。


代码片段(2)

[代码] [Python]代码

01
#-*-
encoding: gb2312 -*-
02
import
string,
threading,time
03
04
def
thread_main(a):
05
global
count,
mutex
06
#
获得线程名
07
threadname
=
threading.currentThread().getName()
08
 
09
for
x
in
xrange
(
0
,
int
(a)):
10
#
取得锁
11
mutex.acquire()
12
count
=
count
+
1
13
#
释放锁
14
mutex.release()
15
print
threadname,
x,count
16
time.sleep(
1
)
17
 
18
def
main(num):
19
global
count,
mutex
20
threads
=
[]
21
 
22
count
=
1
23
#
创建一个锁
24
mutex
=
threading.Lock()
25
#
先创建线程对象
26
for
x
in
xrange
(
0
,
num):
27
threads.append(threading.Thread(target
=
thread_main,
args
=
(
10
,)))
28
#
启动所有线程
29
for
t
in
threads:
30
t.start()
31
#
主线程中等待所有子线程退出
32
for
t
in
threads:
33
t.join()
34
 
35
 
36
if
__name__
=
=
'__main__'
:
37
num
=
4
38
#
创建4个线程
39
main(
4
)

[代码] [Python]代码

01
#-*-
encoding: gb2312 -*-
02
import
threading
03
import
time
04
05
class
Test(threading.Thread):
06
def
__init__(
self
,
num):
07
threading.Thread.__init__(
self
)
08
self
._run_num
=
num
09
 
10
def
run(
self
):
11
global
count,
mutex
12
threadname
=
threading.currentThread().getName()
13
 
14
for
x
in
xrange
(
0
,
int
(
self
._run_num)):
15
mutex.acquire()
16
count
=
count
+
1
17
mutex.release()
18
print
threadname,
x,count
19
time.sleep(
1
)
20
21
if
__name__
=
=
'__main__'
:
22
global
count,
mutex
23
threads
=
[]
24
num
=
4
25
count
=
1
26
#
创建锁
27
mutex
=
threading.Lock()
28
#
创建线程对象
29
for
x
in
xrange
(
0
,
num):
30
threads.append(Test(
10
))
31
#
启动线程
32
for
t
in
threads:
33
t.start()
34
#
等待子线程结束
35
for
t
in
threads:
36
t.join()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: