I am trying to find the best practice for sharing a lock file between multiple classes. Before this I was putting multiple functions inside the same class, so they could share a mutual lock file and a producer/consumer queue. The code is getting a bit longer than I’d like, and I want to break them up into individual classes. When I do this I am unable to share the lock files, or the queues to add/remove the commands from.
I need to have a UI thread that accepts input from the user, and then places the commands into a locked queue that the worker threads can pull from. I would like to place the UI thread and the worker functions into different classes to keep my code nicely organized.
Sorry if this is too vague. Is there a way to do this that doesn’t break good design technique?
If the locks are shared between multiple classes, and the “owner” is not readily identifiable, then place those locks into a class that is shared.
Then when you initialize your classes that utilize the locks, pass them into the constructor. Alternatively, you can have the classes instantiate MyLocks on their own, and then expose it as a property which you can then use in subsequent construction.
The takeaway is to place the locks into their own unit.
Update
An additional benefit of placing multiple locks into their own class is that you can explicitly create methods for seizing and releasing locks. For example:
Now a particular class or operation can request locks, but if they try to grab a lock whose enumerator is less than the lock they are requesting, you can throw an exception. This is important when you require multiple locks to perform an operation as you can ensure that the locks are seized and released in order, which is one of the most common culprits in deadlocks.