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

首頁 > 編程 > Python > 正文

Python中多線程thread與threading的實現方法

2020-02-23 05:38:45
字體:
來源:轉載
供稿:網友

學過Python的人應該都知道,Python是支持多線程的,并且是native的線程。本文主要是通過thread和threading這兩個模塊來實現多線程的。

python的thread模塊是比較底層的模塊,python的threading模塊是對thread做了一些包裝的,可以更加方便的被使用。

這里需要提一下的是python對線程的支持還不夠完善,不能利用多CPU,但是下個版本的python中已經考慮改進這點,讓我們拭目以待吧。

threading模塊里面主要是對一些線程的操作對象化了,創建了叫Thread的class。

一般來說,使用線程有兩種模式,一種是創建線程要執行的函數,把這個函數傳遞進Thread對象里,讓它來執行;另一種是直接從Thread繼承,創建一個新的class,把線程執行的代碼放到這個新的 class里。

我們來看看這兩種做法吧。

一、Python thread實現多線程

#-*- encoding: gb2312 -*-import string, threading, time def thread_main(a):  global count, mutex  # 獲得線程名  threadname = threading.currentThread().getName()   for x in xrange(0, int(a)):    # 取得鎖    mutex.acquire()    count = count + 1    # 釋放鎖    mutex.release()    print threadname, x, count    time.sleep(1) def main(num):  global count, mutex  threads = []   count = 1  # 創建一個鎖  mutex = threading.Lock()  # 先創建線程對象  for x in xrange(0, num):    threads.append(threading.Thread(target=thread_main, args=(10,)))  # 啟動所有線程  for t in threads:    t.start()  # 主線程中等待所有子線程退出  for t in threads:    t.join()   if __name__ == '__main__':  num = 4  # 創建4個線程  main(4)

二、Python threading實現多線程

#-*- encoding: gb2312 -*-import threadingimport time class Test(threading.Thread):  def __init__(self, num):    threading.Thread.__init__(self)    self._run_num = num   def run(self):    global count, mutex    threadname = threading.currentThread().getName()     for x in xrange(0, int(self._run_num)):      mutex.acquire()      count = count + 1      mutex.release()      print threadname, x, count      time.sleep(1) if __name__ == '__main__':  global count, mutex  threads = []  num = 4  count = 1  # 創建鎖  mutex = threading.Lock()  # 創建線程對象  for x in xrange(0, num):    threads.append(Test(10))  # 啟動線程  for t in threads:    t.start()  # 等待子線程結束  for t in threads:    t.join() 

相信本文所述Python多線程實例對大家的Python程序設計能夠起到一定的借鑒價值。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 济宁市| 定日县| 尉犁县| 子长县| 石家庄市| 岱山县| 衡山县| 新兴县| 昆山市| 泸西县| 河津市| 浮梁县| 蓬安县| 天水市| 肇源县| 双桥区| 南部县| 霞浦县| 当涂县| 洪洞县| 汉沽区| 温宿县| 九寨沟县| 太仆寺旗| 吉首市| 石台县| 溆浦县| 苗栗县| 双牌县| 永川市| 鹤庆县| 绵阳市| 富民县| 双流县| 来安县| 鸡泽县| 水富县| 石河子市| 文昌市| 景泰县| 陵水|