Reputation: 35
I'd like to use Active Objects in my embedded realtime project as eloquently described by Herb Sutter, "Prefer Using Active Objects Instead of Naked Threads". I have soft-realtime requirements and a reasonable processor so I'm not too worried about the run-time costs for allocating/de-allocating messages to the Active helper thread. Although I'm stuck with a cross-compiler that doesn't support C++0x features (and to add to that, I can't use Boost), I believe I can implement the general pattern without using TR1 features. But, where I'm getting stuck is how do I properly implement a Future to get an asynchronous result back from the Active object ?..would using Posix mutexes and condition variables be a reasonable approach..how about Posix message queues ?
Upvotes: 0
Views: 607
Reputation: 1975
You might want to take a look at the open source QP/C++ state machine framework and my book "Practical UML Statecharts in C/C++: Event-driven programming for Embedded Systems".
The QP/C++ framework is a very lightweight implementation of the active object computing model for real-time embedded systems with strong support for modeling behavior of active objects as hierarchical state machines (UML statecharts). Specifically to your problem description, the framework has been ported to POSIX threads, where each active object executes in its own p-thread and has its own lightweight event queue that blocks on a private condition variable. Please see the App Note "QP and POSIX" for more information about the port. The complete code for QP is available from SourceForge.net.
Upvotes: 1
Reputation: 68651
A future is essentially a wrapper around a buffer to hold the result, a flag to indicate it is ready, a mutex to protect access to it, and a condition variable for the waiting.
If you know the low-level facilities of the platform, you might be able to optimize it, but that's the basic set.
Of course, the buffer has to be allocated dynamically, so it can be shared between the active object thread and the waiting thread, and destroyed properly, so use something like a ref_counted_ptr<future_data>
.
Getting the value is then something like:
DataType future_data::get() {
pthread_mutex_lock(&mut);
while(!data_ready)
pthread_cond_wait(&cond,&mut);
DataType temp=get_buffer_value();
pthread_mutex_unlock(&mut);
return temp;
}
Though obviously you'll need to add error checking, and account for exceptions.
Upvotes: 1