跳到主要內容

發表文章

目前顯示的是 9月, 2012的文章

Breaking dependency by templates in C++

There are many different ways to break dependencies when doing unit testing in C++. We can use approaches described in the book , including constructor injection, setter injection, extract and override, and...yes, the factory design pattern. They work well in some cases so that we should know the pros and cons of every tricks above. However, they have some common shortcomings: unnecessary run-time indirection by using inheritance (it is getting worse when critical execution path is on the objects) unnecessary interfaces should be added and used. (those interfaces are merely for unit test convenience, not so meaningful in production code) Those traditional tricks used in unit test are based on common OO features. If we focus on C++, can we solve these two problems by different thinking?  I gave template a try by writing a simple word count program. Before we go on, you can clone it to play. The main class (mwc) is a class template with a template parameter contai...

How to terminate threads gracefully when using pthread?

There are several ways to terminate threads. You can use pthread_cancel() to raise a request to them and they would be canceled at some cancellation points, or use pthread_kill() to send a signal to them asynchronously. However, I think they are both not practical . By using pthread_cancel(), we can be sure that the thread would be canceled at some specific POSIX functions. But what if there are other third-party libraries used and there is no way to make sure what POSIX functions are used by them? By using pthread_kill(), it is even worse. We might affect the original read()/write() behaviors when receiving SIGINT. Even we construct safe read()/write() and other functions safe for handling signals, we still have no idea what to cleanup in signal handlers. Signal handling is complex in process, not to mention how to do it well in thread environment which is much younger than the signal mechanism. So how to terminate a thread with minimum effort? It seems only one way: ...