學(xué)過Python的人應(yīng)該都知道,Python是支持多線程的,并且是native的線程。本文主要是通過thread和threading這兩個(gè)模塊來實(shí)現(xiàn)多線程的。
python的thread模塊是比較底層的模塊,python的threading模塊是對thread做了一些包裝的,可以更加方便的被使用。
這里需要提一下的是python對線程的支持還不夠完善,不能利用多CPU,但是下個(gè)版本的python中已經(jīng)考慮改進(jìn)這點(diǎn),讓我們拭目以待吧。
threading模塊里面主要是對一些線程的操作對象化了,創(chuàng)建了叫Thread的class。
一般來說,使用線程有兩種模式,一種是創(chuàng)建線程要執(zhí)行的函數(shù),把這個(gè)函數(shù)傳遞進(jìn)Thread對象里,讓它來執(zhí)行;另一種是直接從Thread繼承,創(chuàng)建一個(gè)新的class,把線程執(zhí)行的代碼放到這個(gè)新的 class里。
我們來看看這兩種做法吧。
一、Python thread實(shí)現(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)建一個(gè)鎖 mutex = threading.Lock() # 先創(chuàng)建線程對象 for x in xrange(0, num): threads.append(threading.Thread(target=thread_main, args=(10,))) # 啟動(dòng)所有線程 for t in threads: t.start() # 主線程中等待所有子線程退出 for t in threads: t.join() if __name__ == '__main__': num = 4 # 創(chuàng)建4個(gè)線程 main(4)
二、Python threading實(shí)現(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)) # 啟動(dòng)線程 for t in threads: t.start() # 等待子線程結(jié)束 for t in threads: t.join()
相信本文所述Python多線程實(shí)例對大家的Python程序設(shè)計(jì)能夠起到一定的借鑒價(jià)值。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
