Home > Mobile >  Create a Lock Function for DataClass
Create a Lock Function for DataClass

Time:11-02

I have a simple dataclass to track a status of my switch like this

@dataclass
class status:
    switch: bool = False

This class is used by two threads so I would like to implement a logic to lock the switch variable change while other thread changing the switch value.

something like

@dataclass
class status:
    lock: bool = False
    switch: bool = False
    
    def setattr(self, val):
        if self.lock is not False:
            self.switch = val

I would like to know if there is a better way to set some logic like this. Something where I do not need to call the method above to check lock on change switch variable.

CodePudding user response:

You should use the existing "Lock". e.g. in the Threading library. You "acquire" the lock when you want one thread to have it and use the locked resource. When another thread tries to acquire the lock it will block until the first thread releases it.

  • Related