Python中多線程thread與threading的實現(xiàn)方法
學(xué)過Python的人應(yīng)該都知道,Python是支持多線程的,并且是native的線程。本文主要是通過thread和threading這兩個模塊來實現(xiàn)多線程的。
python的thread模塊是比較底層的模塊,python的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 thread實現(xiàn)多線程
#-*- 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)
二、Python threading實現(xiàn)多線程
#-*- 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()
# 等待子線程結(jié)束
for t in threads:
t.join()
相信本文所述Python多線程實例對大家的Python程序設(shè)計能夠起到一定的借鑒價值。
- python基于queue和threading實現(xiàn)多線程下載實例
- Python用threading實現(xiàn)多線程詳解
- python使用threading獲取線程函數(shù)返回值的實現(xiàn)方法
- Python 使用threading+Queue實現(xiàn)線程池示例
- Python線程協(xié)作threading.Condition實現(xiàn)過程解析
- Python3 socket即時通訊腳本實現(xiàn)代碼實例(threading多線程)
- python中threading和queue庫實現(xiàn)多線程編程
- Python中threading庫實現(xiàn)線程鎖與釋放鎖
- Python?threading和Thread模塊及線程的實現(xiàn)
相關(guān)文章
正則化DropPath/drop_path用法示例(Python實現(xiàn))
DropPath 類似于Dropout,不同的是 Drop將深度學(xué)習(xí)模型中的多分支結(jié)構(gòu)隨機"失效",而Dropout是對神經(jīng)元隨機"失效"這篇文章主要給大家介紹了關(guān)于正則化DropPath/drop_path用法的相關(guān)資料,需要的朋友可以參考下2022-04-04
selenium設(shè)置瀏覽器為headless無頭模式(Chrome和Firefox)
這篇文章主要介紹了selenium設(shè)置瀏覽器為headless無頭模式(Chrome和Firefox),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
探索Python定時任務(wù)實現(xiàn)高效時間管理
這篇文章主要為大家介紹了探索Python定時任務(wù)高效實現(xiàn)高效時間管理,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2024-01-01
Python中創(chuàng)建字典的幾種方法總結(jié)(推薦)
下面小編就為大家?guī)硪黄狿ython中創(chuàng)建字典的幾種方法總結(jié)(推薦)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-04-04

