Flyweight Locking

Locking is a necessary aspect of multithreading code: it prevents unpredictable behavior and makes sure code that is expected to run synchronously does so. Some situations can leverage lockless code, but not always. When you do need to do a lock you shouldn’t do it carelessly, if you lock a section of code that does some major work (such as database access) and it blocks other pending calls you need to be cognizant that there could be a delay or bottleneck. However, just because we have to lock doesn’t mean we can’t do some simple optimizations depending on what our business logic is. If we only need to lock items per a defined group then we can leverage flyweight locking. Lets go through an example to make this scenario clearer.

Imagine we have a WCF service that signs a student into a class where the student has a name, an … Read more

, , ,

Thread Synchronization With Aspects

This article was originally published at

Aspect-oriented programming is an interesting way to decouple common method level logic into localized methods that can be applied on build. For C#, PostSharp is a great tool that does the heavy lifting of the MSIL rewrites to inject itself in and around your methods based on method tagging with attributes. PostSharp’s offerings are split up into free aspects and pro aspects so it makes diving into aspect-oriented programming easy since you can get a lot done with their free offerings.

One of their free aspects, the method interception aspect, lets you control how a method gets invoked. Using this capability, my general idea was to expose some sort of lock and wrap the method invocation automatically in lock statement using a shared object. This way, we can manage thread synchronization using aspects.

Managing thread synchronization with aspects isn’t a new idea: … Read more

, , , ,

Inter process locking

This article was originally published at

Locking in a single-process multi-threaded application is important enough to understand, but locking in a multi-process application takes on a new level of complexity. Locking makes sure that only one execution unit ever accesses a critical section. This is just fancy way of saying everyone can’t access the same resource at the same time; the critical section is the code path that is synchronized.

Inter process locking

There are resources that can be accessed outside of the logical address space of a process, such as files, and these are available to all processes. If you are writing a multiple process application, and are sharing these resources, you should synchronize them. For these situations, you should use a named mutex. A named mutex registers a global handle in the operating system that any process can request and use.

By giving a mutex a … Read more