python threading模塊操作多線程介紹
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里。我們來看看這兩種做法吧。
#-*- 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
# 創(chuàng)建一個鎖
mutex = threading.Lock()
# 先創(chuàng)建線程對象
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
# 創(chuàng)建4個線程
main(4)
上面的就是第一種做法,這種做法是很常見的,下面是另一種,曾經(jīng)使用過Java的朋友應該很熟悉這種模式:
#-*- encoding: gb2312 -*-
import threading
import 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
# 創(chuàng)建鎖
mutex = threading.Lock()
# 創(chuàng)建線程對象
for x in xrange(0, num):
threads.append(Test(10))
# 啟動線程
for t in threads:
t.start()
# 等待子線程結束
for t in threads:
t.join()
相關文章
Python+OpenCV實戰(zhàn)之實現(xiàn)文檔掃描
這篇文章主要為大家詳細介紹了Python+Opencv如何實現(xiàn)文檔掃描的功能,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2022-09-09
使用Python裝飾器在Django框架下去除冗余代碼的教程
這篇文章主要介紹了使用Python裝飾器在Django框架下去除冗余代碼的教程,主要是處理JSON代碼的一些冗余,需要的朋友可以參考下2015-04-04
Pycharm 2020.1 版配置優(yōu)化的詳細教程
這篇文章主要介紹了更新Pycharm 2020.1 版配置優(yōu)化的詳細教程,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-08-08
對python的unittest架構公共參數(shù)token提取方法詳解
今天小編就為大家分享一篇對python的unittest架構公共參數(shù)token提取方法詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12
python實現(xiàn)將json多行數(shù)據(jù)傳入到mysql中使用
這篇文章主要介紹了python實現(xiàn)將json多行數(shù)據(jù)傳入到mysql中使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-12-12
Python使用crontab模塊設置和清除定時任務操作詳解
這篇文章主要介紹了Python使用crontab模塊設置和清除定時任務操作,結合實例形式分析了centos7平臺上Python安裝、python-crontab模塊安裝,以及基于python-crontab模塊的定時任務相關操作技巧,需要的朋友可以參考下2019-04-04

