現在的位置: 首頁 > 編程語言 > 正文

python 中的線程處理——threading模塊

2018年08月29日 編程語言 ⁄ 共 1618字 ⁄ 字型大小 評論關閉

轉自:http://www.oschina.net/code/snippet_16840_1815

python是支持多線程的,並且是native的線程。主要是通過thread和threading這兩個模塊來實現的。thread是比較底層的模 塊,threading是對thread做了一些包裝的,可以更加方便的被使用。這裡需要提一下的是python對線程的支持還不夠完善,不能利用多 CPU,但是下個版本的python中已經考慮改進這點,讓我們拭目以待吧。

    threading模塊裡面主要是對一些線程的操作對象化了,創建了叫Thread的class。一般來說,使用線程有兩種模式,一種是創建線程要執行的 函數,把這個函數傳遞進Thread對象里,讓它來執行;另一種是直接從Thread繼承,創建一個新的class,把線程執行的代碼放到這個新的 class里。我們來看看這兩種做法吧。

#-*- 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]代碼
view sourceprint?
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() 

抱歉!評論已關閉.