0

I have been trying to find a good way to implement synchronisation in Python. Is the following code alright? If no, then what is wrong with it and how can I improve it?

import threading

class BookingService(threading.Thread):

    # so lock remains static to the class and would be same for all the threads
    lock = None
    
    def __init__(self,name):
        threading.Thread.__init__(self)
        self.name = name
    
        if BookingService.lock == None:
            BookingService.lock = threading.Lock()
    
    def book(self):
    
        with BookingService.lock:
            print("BOOKED! for",self.name)

b1 = BookingService("b1")
b2 = BookingService("b2")
b1.book()
b2.book()

Read about threading module and various ways by which we can do it.

  • You aren't actually using threads, see https://stackoverflow.com/a/2846695/5168011 – Guy Mar 27 '22 at 11:12
  • @Guy What if you just need to write the backend code like what you do in an OOD round and don't know how many threads will be made? How to handle such situations ? – threadNoob123 Mar 27 '22 at 11:25
  • Use a list. Or a [queue](https://docs.python.org/3/library/queue.html) if it's suitable to what yo are doing. – Guy Mar 27 '22 at 11:52

0 Answers0