來源 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()方法中的打印操作並沒有顯示出來,說明已經成為后台進程。