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

首頁 > 編程 > Python > 正文

Python 多線程

2019-11-06 06:36:52
字體:
來源:轉載
供稿:網友

Threading

Python的標準庫提供了兩個模塊:threadthreading,thread是低級模塊,threading是高級模塊,對thread進行了封裝。絕大多數情況下,我們只需要使用threading這個高級模塊。

啟動一個線程就是把一個函數傳入并創建Thread實例,然后調用start()開始執行:

import time,threadingdef loop(): 輸出結果:

thread MainThread is running… thread LoopThread is running… thread LoopThread >>> 1 thread LoopThread >>> 2 thread LoopThread >>> 3 thread LoopThread >>> 4 thread LoopThread >>> 5 thread LoopThread ended. thread MainThread ended.

由于任何進程默認就會啟動一個線程,我們把該線程稱為主線程,主線程又可以啟動新的線程,Python的threading模塊有個current_thread()函數,它永遠返回當前線程的實例。主線程實例的名字叫MainThread,子線程的名字在創建時指定,我們用LoopThread命名子線程。名字僅僅在打印時用來顯示,完全沒有其他意義,如果不起名字Python就自動給線程命名為Thread-1,Thread-2……

Lock

import threading# 3.lock# 假定這是你的銀行存款:balance = 0lock = threading.Lock()def change_it(n): # 先存后取,結果應該為0: global balance balance = balance + n balance = balance - ndef run_thread(n): for i in range(100000): lock.acquire() try: change_it(n) finally: lock.release()t1 = threading.Thread(target=run_thread, args=(5,))t2 = threading.Thread(target=run_thread, args=(8,))t1.start()t2.start()t1.join()t2.join()print balance

Queue

from random import randintfrom time import sleepfrom Queue import Queuefrom myThread import MyThreaddef writeQ(queue): print 'producing object for Q...', queue.put('xxx', 1) print "size now", queue.qsize()def readQ(queue): val = queue.get(1) print 'consumed object from Q... size now', / queue.qsize()def writer(queue, loops): for i in range(loops): writeQ(queue) sleep(randint(1, 3))def reader(queue, loops): for i in range(loops): readQ(queue) sleep(randint(2, 5))funcs = [writer, reader]nfuncs = range(len(funcs))def main(): nloops = randint(2, 5) q = Queue(32) threads = [] for i in nfuncs: t = MyThread(funcs[i], (q, nloops), / funcs[i].__name__) threads.append(t) for i in nfuncs: threads[i].start() for i in nfuncs: threads[i].join() print 'all DONE'if __name__ == '__main__': main()

>

starting writer at: Mon Mar 06 16:34:51 2017 add for Q… size now= 1 starting reader at: Mon Mar 06 16:34:51 2017 sub from Q… size now= 0 add for Q… size now= 1 sub from Q… size now= 0 add for Q… size now= 1 add for Q… size now= 2 writer finished at: Mon Mar 06 16:34:57 2017 sub from Q… size now= 1 sub from Q… size now= 0 reader finished at: Mon Mar 06 16:35:06 2017 all DONE

參考文獻: http://www.tuicool.com/articles/vQQNbiz


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 胶州市| 金沙县| 竹溪县| 响水县| 浦北县| 澜沧| 博罗县| 昭苏县| 清新县| 藁城市| 河间市| 新和县| 华池县| 蓝山县| 静宁县| 库伦旗| 陈巴尔虎旗| 毕节市| 将乐县| 阿坝| 清丰县| 苏州市| 黄陵县| 抚远县| 鹤山市| 汤阴县| 且末县| 清镇市| 托里县| 龙川县| 濮阳市| 垣曲县| 塘沽区| 宜兰市| 高雄市| 长兴县| 长兴县| 广水市| 慈溪市| 綦江县| 麻栗坡县|