python threading模块多线程源码示例(二)
一.思路概述
Python線程創(chuàng)建
使用threading模塊的Thread類的接口如下
class Thread( group=None, target=None, name=None, args=(), kwargs={})
?
需要關(guān)注的參數(shù)是target和args. target 是需要子線程運(yùn)行的目標(biāo)函數(shù),args是函數(shù)的參數(shù),以tuple的形式傳遞。
以下代碼創(chuàng)建一個指向函數(shù)worker的子線程
def worker(tid,account):?
? ? ...?
?
th = threading.Thread(target=worker,args=(i,acc) ) ;
?
啟動這個線程
th.start()
?
等待線程返回或者回收線程資源
threading.Thread.join(th)?
或者th.join()
?
如果你可以對要處理的數(shù)據(jù)進(jìn)行很好的劃分,而且線程之間無須通信,那么你可以使用:創(chuàng)建=》運(yùn)行=》回收的方式編寫你的多線程程序。但是如果線程之間需要訪問共同的對象,則需要引入互斥鎖或者信號量對資源進(jìn)行互斥訪問。
?
下面講講如何創(chuàng)建互斥鎖
創(chuàng)建鎖?
g_mutex = threading.Lock()?
....?
使用鎖?
for ... :?
? ? ? ? #鎖定,從下一句代碼到釋放前互斥訪問?
? ? ? ? g_mutex.acquire()?
? ? ? ? a_account.deposite(1)?
? ? ? ? #釋放?
? ? ? ? g_mutex.release()
二.業(yè)務(wù)需求
模擬一個公交地鐵IC卡繳車費(fèi)的多線程程序
假設(shè)有10個讀卡器,每個讀卡器收費(fèi)器每次扣除用戶一塊錢進(jìn)入總賬中,每個讀卡器每天一共被刷1000000次。賬戶原有100塊。所以最后的總賬應(yīng)該為10000100。
三.源碼實(shí)現(xiàn)
#!/usr/bin/env python
#encoding: utf-8import time, datetime, threading#each worker thread exec 1000000 times
def worker(tid, account):global g_mutexfor i in range(1000000):g_mutex.acquire()if i%500000 == 0:print 'worker thread', tid, 'count', iaccount.deposite(1)g_mutex.release()#account operation class
class Account:def __init__(self, base):self.m_amount = basedef deposite(self, amount):self.m_amount += amount;def withdraw(self, amount):self.m_amount -= amount#main entry point...
if __name__ == '__main__':global g_mutexcount = 0;tm_start = datetime.datetime.now()print 'Main Thread start at:', tm_start#initialize thread poolthread_pool = []#initialize mutexg_mutex = threading.Lock()#init thread itemsacc = Account(100)for i in range(10):t = threading.Thread(target=worker, args=(i, acc));thread_pool.append(t)#start worker threads one by onefor i in range(10):thread_pool[i].start()#reclaim all worker threads resourcefor i in range(10):threading.Thread.join(thread_pool[i])#statisticstm_stop = datetime.datetime.now()print 'count=', acc.m_amountprint 'Main Thread end at:', tm_stopprint 'time consumption ', tm_stop-tm_start
四.運(yùn)行效果截圖
注意在多線程環(huán)境下print輸出要放到互斥鎖下面操作,才不會導(dǎo)致導(dǎo)致各線程的打印信息混亂.
參考文獻(xiàn)
[1].http://blog.csdn.net/liangpz521/article/details/8906861
總結(jié)
以上是生活随笔為你收集整理的python threading模块多线程源码示例(二)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 利用python开源库制作并验证torr
- 下一篇: 使用jtest工具压测Apache Tr