小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

Python threading模塊 - 代碼分享 - 開源中國社區(qū)

 ganame 2011-02-13
Python threading模塊
Sephiroth 發(fā)布于 2010年11月22日 8時 (0評) 2人收藏此代碼, 我要收藏(?)
python是支持多線程的,并且是native的線程。主要是通過thread和threading這兩個模塊來實現(xiàn)的。thread是比較底層的模 塊,threading是對thread做了一些包裝的,可以更加方便的被使用。這里需要提一下的是python對線程的支持還不夠完善,不能利用多 CPU,但是下個版本的python中已經(jīng)考慮改進這點,讓我們拭目以待吧。
    threading模塊里面主要是對一些線程的操作對象化了,創(chuàng)建了叫Thread的class。一般來說,使用線程有兩種模式,一種是創(chuàng)建線程要執(zhí)行的 函數(shù),把這個函數(shù)傳遞進Thread對象里,讓它來執(zhí)行;另一種是直接從Thread繼承,創(chuàng)建一個新的class,把線程執(zhí)行的代碼放到這個新的 class里。我們來看看這兩種做法吧。
標簽: Python

代碼片段(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     # 創(chuàng)建一個鎖
24     mutex = threading.Lock()
25     # 先創(chuàng)建線程對象
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     # 創(chuàng)建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     # 創(chuàng)建鎖
27     mutex = threading.Lock()
28     # 創(chuàng)建線程對象
29     for x in xrange(0, num):
30         threads.append(Test(10))
31     # 啟動線程
32     for t in threads:
33         t.start()
34     # 等待子線程結(jié)束
35     for t in threads:
36         t.join()

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多