python-Multithreading Fun (lock)

Source: Internet
Author: User

Next, the programmer in the code when they feel bored, bored, will think of eating snacks, then if a function:

#!/usr/bin/env python#Coding=utf-8" "" "Import TimeImportThreadingclassMyThread (Threading. Thread):def __init__(self,func,args,name="'): Threading. Thread.__init__(self) self.name=name Self.func=func Self.args=argsdefRun (self):#a thread is about to start.        Print(Self.name +"started #######.")                ifSelf.name = ="listen to the song thread": Matter1 (music)elifSelf.name = ="Coding Thread": Matter2 (number)elifSelf.name = ="Snack Thread": Matter3 (snacks)Print(Self.name +"It's over, ########.")    defMatter1 (music): forIinchRange (0,len (music)):Print("Section"+ STR (i+1) +"The first song is:"+str (music[i]))#Let's say the time for each song is 2s.Time.sleep (2)        Print("Switch to the next song ...")            defmatter2 (number): J= 1 whileJ <=Number :Print("I'm going to write the first"+ STR (j) +"Line Code") J= J+1#assume that each line of code has a time of 1sTime.sleep (1)        Print("write the next line of code ...")        defMatter3 (snacks): forIinchRange (0,len (snacks)):Print("I'm listening to the song."+ str (snacks[i]) +"Snacks")        #Suppose you didn't eat a bag of snacks at 5s intervals .Time.sleep (5)        Print("eat a packet of snacks")            if __name__=='__main__':    #set the song I want to listen toMusic = ['Music1','Music2','music3']        #set the number of lines I want to codeNumber = 4#set the snacks I want to eat forSnacks = ["Spicy Strips","Cola"]        #Start TimeStart =time.time () thing1= MyThread (Matter1,music,"listen to the song thread") Thing2= MyThread (Matter2,number,"Coding Thread") Thing3= MyThread (Matter3,snacks,"Snack Thread") Thing1.start () Thing2.start () Thing3.start () Thing1.join () Thing2.join () Thing3.join () #End TimeEnd =time.time ()Print("the completed time is:", str (end-start))

Results:

Time to complete: 10.001572132110596

However, the programmer has only two hands, then the snack and knock code can not be done at the same time, you need to add a thread lock:

#!/usr/bin/env python#Coding=utf-8" "snacking compared to time, but the program ape has two hands, then snacks and play code can not be done at the same time, then add a line lock thread synchronization is to prevent this, but also introduced the concept of lock. Lock and Rlock can implement thread synchronization. Both objects have the Acquire method and the release method, for those data that require only one thread at a time, You can put its actions between the acquire and the release method. You can understand that something between these two methods will be locked." "Import TimeImportThreading#Open the thread lockLock =Threading. Lock ()classMyThread (Threading. Thread):def __init__(self,target,args,name="'): Threading. Thread.__init__(self) self.name=name#Self.func = FuncSelf.target =Target Self.args=argsdefRun (self):#a thread is about to start.        Print(Self.name +"started #######.")                ifSelf.name = ="listen to the song thread": Matter1 (music)elifSelf.name = ="Coding Thread": Matter2 (number)elifSelf.name = ="Snack Thread": Matter3 (snacks)Print(Self.name +"It's over, ########.")    defMatter1 (music): forIinchRange (0,len (music)):Print("Section"+ STR (i+1) +"The first song is:"+str (music[i]))#Let's say the time for each song is 2s.Time.sleep (2)        Print("Switch to the next song ...")            defmatter2 (number):#Gets the lock, returns True when the lock is successfully obtained, and blocks until the optional timeout parameter is not filled until the lock is acquiredLock.acquire () J= 1 whileJ <=Number :Print("I'm going to write the first"+ STR (j) +"Line Code") J= J+1#assume that each line of code has a time of 1sTime.sleep (1)        Print("write the next line of code ...")    ##释放锁, start the next threadlock.release ()defMatter3 (snacks): Lock.acquire () forIinchRange (0,len (snacks)):Print("I'm listening to the song."+ str (snacks[i]) +"Snacks")        #Suppose you didn't eat a bag of snacks at 5s intervals .Time.sleep (5)        Print("eat a packet of snacks") lock.release ()if __name__=='__main__':    #set the song I want to listen toMusic = ['Music1','Music2','music3']        #set the number of lines I want to codeNumber =4#set the snacks I want to eat forSnacks = ["Spicy Strips","Cola"]        #Start TimeStart =time.time () thing1= MyThread (Matter1,music,"listen to the song thread") Thing2= MyThread (Matter2,number,"Coding Thread") Thing3= MyThread (Matter3,snacks,"Snack Thread") Thing1.start () Thing2.start () Thing3.start () Thing1.join () Thing2.join () Thing3.join () #End TimeEnd =time.time ()Print("the completed time is:", str (end-start))

Completion time:

Time to complete: 14.000801086425781

Results:

Listen to the song thread started ####### 1th song is: Music1 code thread started ####### I'm going to write the 1th line of code snack thread started  ####### write the next line of code ... I'm going to write the 2nd line of code to switch to the next song ... The 2nd song is: Music2 write the next line of code ... I'm going to write the 3rd line of code to write the next line of code ... I'm going to write the 4th line of code to switch to the next song ... The 3rd song is: Music3 write the next line of code ... Coding thread is over ######## I'm listening to the song eat spicy snacks switch to the next song ... Listen to the song thread's over. ######## ate a packet of snacks I was listening to the song Eat Coke Snacks eat a packet of snacks snack thread end ######## time to complete: 14.000801086425781

python-Multithreading Fun (lock)

Related Article

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.