时间:2021-07-01 10:21:17 帮助过:22人阅读
启动这个线程
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)
注意,先不用互斥锁进行临界段访问控制,运行结果如下:
从结果看到,程序确实是多线程运行的。但是由于没有对对象Account进行互斥访问,所以结果是错误的,只有3434612,比原预计少了很多。
打开锁后:
这次可以看到,结果正确了。运行时间比不进行互斥多了很多,不过这也是同步的代价。
同时发现,写多线程,多进程类的程序,不能用自带的idle来运行。会有错误。