Multi-Threading Benefits :
Multiple tasks can be run at the same time
but when multiple Threads Simultaneous Access when you share data, you may cause data is out of sync , even wrong!
So, do not use the thread lock and may cause errors
Buy Tickets-Thread lock
[Email protected]~]# cat test.py
#-*- coding:utf-8 -*-import threadingimport time tickets = range (1,10) def buy_ticket (station): while true:mylock.acquire () #加线程锁if len (tickets) == 0: mylock.release () #释放线程锁, do not lock end thread break;ticket = Tickets[-1]time.sleep (1) print "%s buy ticket no.%d" % (station, ticket) del tickets[-1]mylock.release () #释放线程锁time. Sleep (1) class mythread (threading. Thread):d ef __init__ (self, station): Threading. After the thread.__init__ (self) self.station = station# thread is started, the Self.run () method Def run (self) is executed: Buy_ticket ( Self.station) # Create a thread lock mylock = threading. Lock () # Create new Thread T1t1 = mythread ("Guangzhou") t2 = mythread ("Shenzhen") t1.start () #启动线程t2. Start () print " Thread started " print ' end. '
Results:
[[Email protected]~]# python test.py
Python thread lock