
On Sat, 11 Jun 2005 00:34:08 +0300 "Peter Dimov" <pdimov@mmltd.net> wrote:
Let's take a step back. Why would I use the message queue at all in a single threaded program? Its whole purpose is to enable inter-thread communication, right?
How about another step back. The initial query was about using mutex and condvar together when null_mutex is defined. Obviously, if you are doing this, you are trying to write generic code, which can be used in both a single and multi threaded environment (otherwise, why even care about null_mutex). As one example, I suggested a message queue (there are many other examples of writing generic code for both single and multi threaded environments). If we can agree that writing the same code for single and multi threaded applications is a good thing (or at least, not a terrible thing), then we can see the use of null_mutex. However, in some cases, code will use a condition variable. We do not want to disqualify compilation of this code, yet we know that if the code path is executed in a single threaded environment (or "unlocking" environment), it would be a "bad thing" to wait. Thus, I think throwing an exception is a reasonable course of action if a condition variable is waited upon with a null_mutex. Now, taking one step forward from there (and one back from where I was prior to this email), I should be right where you want me ;-) Why would I want to use a message queue in a single-threaded application? I have several answers, but the biggest one that relates to this thread (and boost), is code reuse. Consider an application written to a user level model similar to SVr4 streams. Each "module" process messages off a message queue. You can write all application modules using the same interface. Also, consider a network application. If your "reader" modules are written to put their data on a message queue, then you can easily chain protocol layers. If you are using a single thread or multiple threads, you still use the same code. If you are multithreaded, another thread will slurp up the message and process it as soon as it is available (and the condvar is signalled, and the lock is released). If you are single threaded, the message will be processed when the controling code path decides to process the queue. In either case, the main processing code is the same, and the application specific module code is the same, providing a nice bit of code reuse. Yes, there is a little overhead in the message queue, but even in a multithreaded environment, you should not be putting heavy weight messages on the queue.