日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

python threading模块多线程源码示例(二)

發(fā)布時(shí)間:2023/11/27 生活经验 45 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python threading模块多线程源码示例(二) 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

一.思路概述

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)建一個(gè)指向函數(shù)worker的子線程
def worker(tid,account):?
? ? ...?
?
th = threading.Thread(target=worker,args=(i,acc) ) ;
?
啟動這個(gè)線程
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ù)需求

模擬一個(gè)公交地鐵IC卡繳車費(fèi)的多線程程序
假設(shè)有10個(gè)讀卡器,每個(gè)讀卡器收費(fèi)器每次扣除用戶一塊錢進(jìn)入總賬中,每個(gè)讀卡器每天一共被刷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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。