views:

210

answers:

3

Hi, I'm trying to track down the source of a particular piece of coding advice I once read. I'm currently working with a class that has a lot of threading around a single shared resource, controlled by a mutex. I just spent a week trying to debug the damn code, because it's difficult to spot sub-functions which don't self-lock, and one was writing during a read. Occasionally. Under a near impossible to predict set of circumstances.

I never want to deal with this again, and I think I've devised a guideline which should reduce this kind of faff in the future, which is to rename all functions that access the resource, adding a suffix:

  1. "NeedsLock": Accesses the resource but doesn't lock. (i.e. This function must be run inside a lock).
  2. "Locks": Locks and accesses the resource (i.e. This function must NOT be run inside a lock)

The problem is that I know I've read this advice somewhere, and when I have to back up my decision (because Hungarian Notation? What is this, the 60's?), I'd like to be able to point to the source. I also want to check that I'm not missing anything important from the original idea.

Does this style seem familiar to anyone?

+1  A: 

There's an article in a January 2009 MSDN Magazine article that references this technique:

Round-Robin Access To The ThreadPool

At that point, RemoveQueueNeedsLock is used to remove the target queue from the queues list and potentially update the next queue pointer in case it's now out of range.

Note that this method does not use a lock internally but accesses shared state; hence I've named the method with a "NeedsLock" suffix to remind myself that it needs to be called while the lock is held.

GalacticJello
I saw that article, but it sounds different than what he is describing, as this is just a queue method and the NeedsLock part is just to remind you when you can call this.
James Black
It's a good example of this pattern being used, but it's not really the whole pattern.
deworde
+1  A: 

More in the theoretical context, one of the best references you can find is Milner's Communicating and Mobile Systems: The Pi Calculus.

More pragmatic what about Chapter Four "Eight Simple Rules for Designing Multithreaded Applications" from the book "The Art of Concurrency"

Let us know if you find the source you're looking for.

msalvadores
A: 

All right, you didn't mention the environment your program's working in. Is it feasible to run the program in gdb, and put a watch on the shared resource in order to track down all the sub-functions/places in code that refer to it?

-- edited --

Regarding the future-proof solution: Is it feasible to hide the mentioned resource, and allow access to it via getter/setter? (that would probably require refactoring your code in many places)

hlynur
Yeah, just about. But that merely allows us to track down the current bugs, and I'm looking to future-proof the function.
deworde