Concurrent, Multi-Core Programming on Windows and .NET (Part IV -- Synchronization Best Practices: Stephen Toub)

Lock Consistently
DO: Lock over all shared mutable states
DO: Ensure you always use the same lock to protect the same data
DO: Comment on how state is protected

Lock for the Right Duration
DO: Lock over the entire invariant
DON'T: Lock for longer than absolutely necessary

Note: in .NET 1.1, there are non-generic synchronized types (e.g. ArrayList.Synchronized)

Make Critical Regions Short and Sweet
DO: Minimize the time you hold on to a lock
DON'T: Call others' code while you hold locks
DON'T: block while you hold locks

Encapsulate Your Locks
DON'T: Use public lock objects
DON'T: Lock on Types or Strings
Strings and types are domain-neutral constructs that can be shared across multiple app domains
Note: there is a Synchronized attribute; the C# compiler emits this attribute on event handlers

Avoiding Deadlocks
DO: Acquire locks in a consistent order; deadlock is created when cycles are possible
Leveled locks help solve this problem (check for Joe Duffy's MSDN article)
Deadlock detection can also be used to monitor for this problem; expensive but possible
- see Stephen Toub's MSDN article for DDMonitor
- Joe Duffy's MSDN article on implementing your own CLR host
- WaitChainTraversal API introduced in Vista

Locking Miscellany
DO: Document your locking policy, especially for public APIs
DO: Use a reader/writer lock if readers are common; Vance Morrison's MeasureIt is a good tool for performance measurement
DO: Prefer lock-based code to lock-free code; involves intensive code review
DO: Prefer Monitors over kernel synchronization
AVOID: Lock recursion in your designs
DON'T: Build your own lock

ThreadPool Best Practices
AVOID: Writing your own thread pools
DO: Leverage the framework ThreadPool whenever possible
See MSDN articles for layering cancellation, prioritization, round robin support, throttling on top of ThreadPool

Print | posted @ Sunday, October 26, 2008 9:24 PM

Comments on this entry:

No comments posted yet.

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: