Good example of livelock?

后端 未结 11 1753
后悔当初
后悔当初 2021-01-29 18:44

I understand what livelock is, but I was wondering if anyone had a good code-based example of it? And by code-based, I do not mean \"two people trying to get p

11条回答
  •  星月不相逢
    2021-01-29 19:08

    Python version of jelbourn's code:

    import threading
    import time
    lock = threading.Lock()
    
    class Spoon:
        def __init__(self, diner):
            self.owner = diner
    
        def setOwner(self, diner):
            with lock:
                self.owner = diner
    
        def use(self):
            with lock:
                "{0} has eaten".format(self.owner)
    
    class Diner:
        def __init__(self, name):
            self.name = name
            self.hungry = True
    
        def eatsWith(self, spoon, spouse):
            while(self.hungry):
                if self != spoon.owner:
                    time.sleep(1) # blocks thread, not process
                    continue
    
                if spouse.hungry:
                    print "{0}: you eat first, {1}".format(self.name, spouse.name)
                    spoon.setOwner(spouse)
                    continue
    
                # Spouse was not hungry, eat
                spoon.use()
                print "{0}: I'm stuffed, {1}".format(self.name, spouse.name)
                spoon.setOwner(spouse)
    
    def main():
        husband = Diner("Bob")
        wife = Diner("Alice")
        spoon = Spoon(husband)
    
        t0 = threading.Thread(target=husband.eatsWith, args=(spoon, wife))
        t1 = threading.Thread(target=wife.eatsWith, args=(spoon, husband))
        t0.start()
        t1.start()
        t0.join()
        t1.join()
    
    if __name__ == "__main__":
        main()
    

提交回复
热议问题