Python多线程有很广泛的应用空间,首先我们来看看如何进行相关的应用。下面我们就来看看在生活中的案例。希望大家有些启发。最后,模拟一个公交地铁IC卡缴车费的Python多线程程序。

创新互联-专业网站定制、快速模板网站建设、高性价比善右网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式善右网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖善右地区。费用合理售后完善,10余年实体公司更值得信赖。
有10个读卡器,每个读卡器收费器每次扣除用户一块钱进入总账中,每读卡器每天一共被刷10000000次。账户原有100块。所以最后的总账应该为10000100。先不使用互斥锁来进行锁定(注释掉了锁定代码),看看后果如何。
- import time,datetime
 - import threading
 - def worker(a_tid,a_account):
 - global g_mutex
 - print "Str " , a_tid, datetime.datetime.now()
 - for i in range(1000000):
 - #g_mutex.acquire()
 - a_account.deposite(1)
 - #g_mutex.release()
 - print "End " , a_tid , datetime.datetime.now()
 - class Account:
 - def __init__ (self, a_base ):
 - self.m_amount=a_base
 - def deposite(self,a_amount):
 - self.m_amount+=a_amount
 - def withdraw(self,a_amount):
 - self.m_amount-=a_amount
 - if __name__ == "__main__":
 - global g_mutex
 - count = 0
 - dstart = datetime.datetime.now()
 - print "Main Thread Start At: " , dstart
 - #init thread_pool
 - thread_pool = []
 - #init mutex
 - g_mutex = threading.Lock()
 - # init thread items
 - acc = Account(100)
 - for i in range(10):
 - th = threading.Thread(target=worker,args=(i,acc) ) ;
 - thread_pool.append(th)
 - # start threads one by one
 - for i in range(10):
 - thread_pool[i].start()
 - #collect all threads
 - for i in range(10):
 - threading.Thread.join(thread_pool[i])
 - dend = datetime.datetime.now()
 - print "count=",acc.m_amount
 - print "Main Thread End at: " ,dend , " time span " ,
 
dend-dstart;
上面就是对相关Python多线程技术的介绍。
【编辑推荐】
Copyright © 2009-2022 www.wtcwzsj.com 青羊区广皓图文设计工作室(个体工商户) 版权所有 蜀ICP备19037934号