I have the following pseudo code:
class A:
mutex lockForB
class B:
def __init__(self, A): //the type of A is class A
lock(A.lockForB)
# ...
unlock(A.lockForB)
# other function have the same locking
I understand from oop point of view it is very bad idea to use such design, but if I create lock inside class B I will not be able to put lock on creator of the class B. Is there any better design for this? Thanks in advance.
I have no idea what you’re trying to accomplish. It’s unlikely that a class level lock is what you want but your pseudocode is not so far from the actual code so I’ll just fill in the blanks. Honestly, without some idea what you’re attempting to synchronize access to it’s going to be a challenge to help you.
So that code will work. lockForB is just a class level attribute on A so it is shared between all instances of A. However, in cases where I’ve seen folks use class level locks like this it is usually to prevent the class that owns the lock from being put into an inconsistent state where you have 2 seemingly unrelated classes sharing a lock.
Without context to help understand what you’re attempting to synchronize access to it’s really hard to tell you why this couldn’t be written like this: