Python thread lock

Source: Internet
Author: User


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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.