国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python多線程中阻塞(join)與鎖(Lock)使用誤區解析

2020-02-22 23:53:39
字體:
來源:轉載
供稿:網友

關于阻塞主線程

join的錯誤用法

Thread.join() 作用為阻塞主線程,即在子線程未返回的時候,主線程等待其返回然后再繼續執行.

join不能與start在循環里連用
以下為錯誤代碼,代碼創建了5個線程,然后用一個循環激活線程,激活之后令其阻塞主線程.

threads = [Thread() for i in range(5)]for thread in threads: thread.start() thread.join()

執行過程:

1. 第一次循環中,主線程通過start函數激活線程1,線程1進行計算.
2. 由于start函數不阻塞主線程,在線程1進行運算的同時,主線程向下執行join函數.
3. 執行join之后,主線程被線程1阻塞,在線程1返回結果之前,主線程無法執行下一輪循環.
4. 線程1計算完成之后,解除對主線程的阻塞.
5. 主線程進入下一輪循環,激活線程2并被其阻塞…

如此往復,可以看出,本來應該并發的五個線程,在這里變成了順序隊列,效率和單線程無異.

join的正確用法

使用兩個循環分別處理start和join函數.即可實現并發.

threads = [Thread() for i in range(5)]for thread in threads: thread.start()for thread in threads: thread.join()

time.sleep代替join進行調試

之前在一些項目里看到過這樣的代碼,使用time.sleep代替join手動阻塞主線程.
在所有子線程返回之前,主線程陷入無線循環而不能退出.

for thread in threads: thread.start()while 1: if thread_num == 0: break time.sleep(0.01)

關于線程鎖(threading.Lock)

單核CPU+PIL是否還需要鎖?

非原子操作 count = count + 1 理論上是線程不安全的.
使用3個線程同時執行上述操作改變全局變量count的值,并查看程序執行結果.
如果結果正確,則表示未出現線程沖突.

使用以下代碼測試

# -*- coding: utf-8 -*-import threadingimport timecount = 0class Counter(threading.Thread): def __init__(self, name): self.thread_name = name super(Counter, self).__init__(name=name) def run(self): global count for i in xrange(100000):  count = count + 1counters = [Counter('thread:%s' % i) for i in range(5)]for counter in counters: counter.start()time.sleep(5)print 'count=%s' % count

運行結果:

count=275552

事實上每次運行結果都不相同且不正確,這證明單核CPU+PIL仍無法保證線程安全,需要加鎖.

加鎖后的正確代碼:

# -*- coding: utf-8 -*-import threadingimport timecount = 0lock = threading.Lock()class Counter(threading.Thread): def __init__(self, name): self.thread_name = name self.lock = threading.Lock() super(Counter, self).__init__(name=name) def run(self): global count global lock for i in xrange(100000):  lock.acquire()  count = count + 1  lock.release()counters = [Counter('thread:%s' % i) for i in range(5)]for counter in counters: counter.start()time.sleep(5)print 'count=%s' % count            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 黄陵县| 尉犁县| 聂拉木县| 晋城| 荆州市| 太湖县| 雷波县| 进贤县| 景谷| 黔西县| 望奎县| 来安县| 磐石市| 沧源| 随州市| 安徽省| 合阳县| 揭西县| 漠河县| 襄垣县| 璧山县| 黄冈市| 明星| 昂仁县| 十堰市| 宁陵县| 和顺县| 商丘市| 西城区| 平安县| 横山县| 昌乐县| 潼南县| 松桃| 炎陵县| 紫云| 甘洛县| 塔河县| 元朗区| 嘉善县| 法库县|