Re: C++ threading could be so simple...
Kian Karas wrote:
I will appreciate some feedback on these thoughts:
Threads with undeterministic communication (semi-random input/output)
are usually (and best) implemented with some kind of message loop.
..........
void thread_a() {
// ...
thread_b_queue.push_back(make_message(&foo, 42));
// ...
}
void thread_b() {
while (true) {
MessageBase* msg = thread_b_queue.get(); // Blocking call
msg->dispatch(); // Thread 'b' executes the call to 'foo(42)'
delete msg;
}
}
......
This is pretty inefficient.
I think this would be better:
virtual void produce() {
// ... some blocking mechanism, like io,
// process data then
_queue.push_back(make_message(&foo,42));
// ...
}
void consume() {
while(auto_ptr<MessageBase> msg = _queue.get()) // blocks only if
locked by other thread
msg->dispatch(); // executes the call to 'foo(42)'
}
in base Thread class:
int Thread::run()
{
while(!shutdown())
{
produce(); // waits for data
consume(); // performs work
}
return 0;
}
In this way you can avoid condition variable in _queue.get() which
adds large overhead because threads have to sleep twice, producer on
io stream, consumer on condition variable...
With this approach you can get 40k requests per second instead just
4k , for example on cygwin, windows...
Greets
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]