Thread-Safe Interface

来源:互联网 发布:centos squid 编辑:程序博客网 时间:2024/05/16 16:13
 This article is extracted from POSA2 as a reading note.

This pattern is really a shock for me. I met it in some projects before but I cannot tell why they code in this way. Now I do know the exact reason to apply this pattern.

The Thread-Safe Interface design pattern minimizes locking overhead and ensures that intra-component method calls do not incur 'self-deadlock' by trying to reacquire a lock that is held by the component already.

Structure all components that process intra-component method invocations according two design conventions:

Interface methods check: All interface methods, such as C++ public methods, should only acquire/release component lock(s), thereby performing synchronization checks at the 'border' of the component. After the lock is acquired, the interface method should forward immediately to an implementation method, which performs the actual method functionality. After the implementation method returns, the interface method should release the lock(s) before returning control to the caller.

Implementation methods trust: Implementation methods, such as C++ private and protected methods, should only perform work when called by interface methods. They therefore trust that they are called with the necessary lock(s) held and should never acquire or release lock(s). Implementation methods should also never call 'up' to interface methods, because these methods acquire lock(s).

According to the design conventions described above, you need to determine the interface and corresponding implementation methods. The interface methods define the public API of the component. For each interface method, define a corresponding implementation method.

It's really something, right?