How to do it...

The steps involved are as follows:

  1. We introduced the Box class, which provides the add() and remove() methods that access the execute() method in order to perform the action to add or delete an item, respectively. Access to the execute() method is regulated by RLock():
import threading
import time
import random

class Box:
def __init__(self):
self.lock = threading.RLock()
self.total_items = 0

def execute(self, value):
with self.lock:
self.total_items += value

def add(self):
with self.lock:
self.execute(1)

def remove(self):
with self.lock:
self.execute(-1)
  1. The following functions are called by the two threads. They have the box class and the total number of items to add or to remove as parameters:
def adder(box, items):
print("N° {} items to ADD ".format(items))
while items:
box.add()
time.sleep(1)
items -= 1
print("ADDED one item -->{} item to ADD ".format(items))

def remover(box, items):
print("N° {} items to REMOVE ".format(items))
while items:
box.remove()
time.sleep(1)
items -= 1
print("REMOVED one item -->{} item to REMOVE
".format(items))
  1. Here, the total number of items to add or to remove from the box is set. As you can see, these two numbers will be different. The execution ends when both the adder and remover methods accomplish their tasks:
def main():
items = 10
box = Box()

t1 = threading.Thread(target=adder,
args=(box, random.randint(10,20)))
t2 = threading.Thread(target=remover,
args=(box, random.randint(1,10)))

t1.start()
t2.start()

t1.join()
t2.join()

if __name__ == "__main__":
main()
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.120.109