综述
2.使用Jython 或 IronPython,可以得到真正的多线程。
…
th = threading.Thread(target=worker,args=(i,acc) ) ;
或者th.join()
g_mutex = threading.Lock()
….
使用锁
for … :
#锁定,从下一句代码到释放前互斥访问
g_mutex.acquire()
a_account.deposite(1)
#释放
g_mutex.release()
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;
Str 0 2009-01-13 00:17:55.312000
Str 1 2009-01-13 00:17:55.453000
Str 2 2009-01-13 00:17:55.484000
Str 3 2009-01-13 00:17:55.531000
Str 4 2009-01-13 00:17:55.562000
Str 5 2009-01-13 00:17:55.609000
Str 6 2009-01-13 00:17:55.640000
Str 7 2009-01-13 00:17:55.687000
Str 8 2009-01-13 00:17:55.718000
Str 9 2009-01-13 00:17:55.781000
End 0 2009-01-13 00:18:06.250000
End 1 2009-01-13 00:18:07.500000
End 4 2009-01-13 00:18:07.531000
End 2 2009-01-13 00:18:07.562000
End 3 2009-01-13 00:18:07.593000
End 9 2009-01-13 00:18:07.609000
End 7 2009-01-13 00:18:07.640000
End 8 2009-01-13 00:18:07.671000
End 5 2009-01-13 00:18:07.687000
End 6 2009-01-13 00:18:07.718000
count= 3434612
Main Thread End at: 2009-01-13 00:18:07.718000 time span 0:00:12.422000
Str 0 2009-01-13 00:26:12.156000
Str 1 2009-01-13 00:26:12.390000
Str 2 2009-01-13 00:26:12.437000
Str 3 2009-01-13 00:26:12.468000
Str 4 2009-01-13 00:26:12.515000
Str 5 2009-01-13 00:26:12.562000
Str 6 2009-01-13 00:26:12.593000
Str 7 2009-01-13 00:26:12.640000
Str 8 2009-01-13 00:26:12.671000
Str 9 2009-01-13 00:26:12.718000
End 0 2009-01-13 00:27:01.781000
End 1 2009-01-13 00:27:05.890000
End 5 2009-01-13 00:27:06.046000
End 7 2009-01-13 00:27:06.078000
End 4 2009-01-13 00:27:06.109000
End 2 2009-01-13 00:27:06.140000
End 6 2009-01-13 00:27:06.156000
End 8 2009-01-13 00:27:06.187000
End 3 2009-01-13 00:27:06.203000
End 9 2009-01-13 00:27:06.234000
count= 10000100
Main Thread End at: 2009-01-13 00:27:06.234000 time span 0:00:54.078000