For Brew Developers, There Are New Kids in Town: IThread & IRscPool, Part 2

November 6, 2003

Abstract:

We will continue our journey, trying to avoid the limitations discovered in the last installment. We'll start with a short evaluation of the techniques used in the first article, hopefully allowing us to refine our initial approach. Some design variations will be presented too.

Known Facts

Using IThread and IRscPool from C is straightforward. Together with the ThreadUtil library, they offer a solid solution for a "task-oriented" style of programming in BREW. Using them from C++ is less obvious, and this because at least two reasons:

IRscPool was intended as a "memory arena" with no knowledge about object construction and destruction (other than IBase-derived objects, but this is a BREW construct not very useful in C++). Using IRscPool implies using placement new and explicit destruction—an extremely inconvenient detail.

IThread is poorly equipped for asynchronous cancellation—the stack is not unwound and this simply forbids the use of automatic objects with nontrivial destructors.

Let's start from the bottom up and try to figure out the minimal artifacts needed to solve or at least alleviate these problems.

Safe asynchronous cancellation implies that at any time the thread has to be prepared to respond to an interrupt signal by properly cleaning the resources, in a predictable and consistent manner, leaving the system in a stable state. BREW threads are cooperative—an additional bonus: An interrupt signal is guaranteed to be received in a stable state. A solution might be to intercept the interrupt call, do the necessary clean up on behalf of the thread, and pass control back to the caller. What's needed?

A "god" instance having knowledge of the threads and announcing them when an interrupt occurs

A mechanism to check for interrupts

A blocking call to unwind the stack

A way to correctly destruct objects involved in the execution of a particular thread

If comparing a., d., and Problem 1, we can easily see that they share a common request for a container with special management properties: Other than proper cleanup work, the container should intercept and dispatch the calls. Such a container solves Problem 1 and puts Problem 2 on a fast track.

IRelease defines a class of interruptible resources, capable of sending notifications and identifiable by ID and type. ResourceRegistry stores and manipulates IRelease-based resources, closely following IRelease exposed functionality. We will go into implementation details a little bit later.

In the previous article, IThread was packaged in a wrapper—BThread—and the advantages of such an approach were fully explained. This time, as promised, BThread (renamed BThreadT) will have the benefit of more functionality, resembling Java Thread implementation. This decision is somehow arbitrary but not without merits: It keeps the implementation simple and focused on the virtues of cooperative multithreading (for example mutual exclusion is naturally achieved in such "serialized" systems—there is rarely any need for a "synchronized" keyword or a mutex). So, for example, we will find, wait, and notify.

BThreadT implements IRelease—meaning, among other things already discussed, that it is interruptible and notifiable. It exposes the following public functionality:

Every BThreadT has an associated "runnable"—the mysterious R in the template list. A runnable is basically a functor implementing the thread's loop. An alternative design, based on dynamic polymorphism, is also possible: "Runnable" R is a descendent of an IRunnable in this case. Other than a slight performance penalty affecting the dynamic version (static vs. dynamic, functor vs. virtual callback) and the type coupling that might be counterproductive in some usage scenarios, the two designs are fully equivalent.

Internally, BThreadT hosts an interesting method: checkInterrupt(). Almost all the public methods do a check of the interrupted status (isInterrupted_) (whose change might be trigger by interrupt()) via checkInterrupt. If isInterrupted is true, an EINTR error is raised. That's why all the methods usually returning void return an int in this implementation and their return code should be checked for EINTR.

This is an example of a very simple function to be executed by a BThreadT. Please note the automatic objects created on the stack—potential problems for asynchronous cancellations. When user exits the application (unexpectedly or not), the ResourceRegistry is destroyed, triggering a global interrupt. The main advantage of ResourceRegistry over a pool is that in a Registry resources are kept as individual, enumerable instances—and this is how interrupts are propagated to the active threads. Interestingly enough, an interrupt has to be synchronous (we are in the middle of a destructor activity, remember?). That's why we have the following implementation:

and isInterrupted is set to true. When yield() is checked against EINTR, actually it verifies whether or not isInterrupted was set to true. If this is true, the code exits normally via a break, the stack is unwound correctly, and the objects are properly destructed.

Other implementation details:

A thread is identifiable by the associated ResourceRegistry id (basically, the thread position in the Registry container). There is a getIdD() method capable of returning the id of a thread after its creation.

All the operations on threads can be executed at a global or an instance level. Instance level is by id as described before. At the global level resources, can be grouped by type—analogous to getId() there is a getType(); For example threads have (an arbitrary) type 100. That's why all xxxAll (unregisterAll() is a notable exception) methods accept an additional type parameter.

"join" was implemented as a static member function and a specialized W_AEECBK structure wraps its callbacks in a RAII fashion. It accepts static PFNNOTIFY functions only. Passing member functions as entry points is not trivial, due to the fact that we have to make known the class type to BThreadT. A possible implementation can be found in BThreadT.h:

template <class Y, class T>
struct pkAEECBK

Other similar strategies can be used—one, accepting functions with one or more parameters, being presented for example in [1].

The above code simply iterates a cursor, yielding every 10 counts. yield() is a mandatory action—is how BREW regains control and "pets" the watchdog. As described before, we check explicitly for interrupts (t->yield() == EINTR).

This example starts two threads. The first one waits after 30 cycles, being explicitly notified by the second after 100 cycles. After that, the second one uses a wait/notifyAll mechanism to join the first one.

Future Enhancements

The current implementation is far from exhibiting the API of a normal thread. Interested users can easily adapt additional ThreadUtil functionality to be used by BThreadT or can create their own. For example, a Mutex (if ever needed!) might be easily implemented by using ResourceRegistry for cancellation.