You are not logged in.
Hey guys,
I'm currently writing a generic, reference counted, and thread safe collection of data structures in C. Mostly its for the practice of writing a larger C project, although I figure I'll get some personal use out of it as well.
All of my data structures contain a base element that is used in reference counting, and a custom semaphore/mutex. This base element also is the "generic" object type for the data structures. There is a simple thread synchronization API that is provided for use with the data structures as well. I'm uncertain to where I would like to implement thread safe operations on these data structures. At the moment there are two possibilities I am considering:
1) Conceal all thread synchronization within the data structures methods. So if I were to call a function on such a data structure, the function would take care of locking/unlocking the mutex protecting the data structure as needed. This would make using the objects very simple, all methods on an object are thread safe no matter what. The issue with this that the synchronization a data structure would depend on whether the contained objects also implement proper synchronization, and that it hides the synchronization API from view until new data structures are created.
2) Provide the synchronization API for external application, where a data structure must be locked, used, and then unlocked. The locking/unlocking code is now exposed to the programmer and must be called directly. At the same time a container class can directly enforce synchronization on all elements contained within, eliminating containers dependence on contained synchronization.
I should also mention that new data structures would need to use the same synchronization API. This API is fairly simple and the complexity of applying it in solutions 1 or 2 is equivalent.
My question is mostly opinion based: I know that I can implement either solution, but I'm uncertain as to which is preferable. If you were to use a similar library where in the code would you prefer to deal with thread synchronization: internally within data structure functions, or externally with direct control over when locks and unlocks occur, and why?
EDIT: clarity and spelling. oops.
Last edited by tyler.heck (2012-07-09 05:16:20)
Offline
@tyler.heck: Don't make synchronisation intrinsic to data structures. Synchronizing every operation on a data structure regardless of whether its actually required has severe impacts on performance.
Offline
I'd be worried that if the programmer didn't see the locking, he'd be likely to thoughtlessly add in lockups. But if you anticipate being the only user, you might have an easy enough time keeping track of it.
Offline