开发者

Adding locks to the class by composition

I'm writing thread-safe class in C++. All of its public methods use locks (non-recursive spin locks). Private methods are lock-free. So, everything should be OK: user calls public method, it locks object and then does the work through private methods. But I got dead lock when a public method calls another public method. I开发者_如何转开发've read that recursive mutexes are bad, cause it's difficult to debug them. So I use C's stdio way: public method Foo() only locks the object and calls Foo_nolock() to do the whole work. But I don't like these _nolock() methods. I think it duplicates my code. So I've got an idea: I'll make lock-free class BarNoLock, and thread-safe class Bar that has only one member: an instance of BarNoLock. And all Bar's methods will only lock this member and call it's methods. Is it a good idea or maybe there are some better patterns/practices? Thanks. Update: I know about pimpl and bridge. I ask about multi-threading patterns, not OOP.


I'm not sure why recursive mutexes would be considered bad, see this question for a discussion of them.

Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)

But I don't think that's necessarily your problem because Win32 critical sections support multiple entries from the same thread without blocking. From the doc:

When a thread owns a critical section, it can make additional calls to EnterCriticalSection or TryEnterCriticalSection without blocking its execution. This prevents a thread from deadlocking itself while waiting for a critical section that it already owns. To release its ownership, the thread must call LeaveCriticalSection one time for each time that it entered the critical section. There is no guarantee about the order in which waiting threads will acquire ownership of the critical section

So maybe you were doing something else wrong when you were deadlocking yourself? Having to work around not deadlocking yourself on the same mutex from the same thread with weird function call semantics is not something you should have to do.


Looks like you have reinvented the Bridge Pattern. Sounds perfectly in order.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜