Home > Articles > Programming > C/C++

This chapter is from the book

This chapter is from the book

13.8 Thread Termination

There's something unusual about the examples given so far, in particular writer defined on page 402 and fileWriter defined on the facing page: both functions contain an infinite loop. In fact, a closer look at the file copy example reveals that main and fileWriter understand each other well regarding copying things around but never discuss application termination; in other words, main does not ever tell fileWriter, "We're done; let's finish and go home."

Termination of multithreaded applications has always been tricky. Threads are easy to start, but once started they are difficult to finish; the application shutdown event is asynchronous and may catch a thread in the middle of an arbitrary operation. Low-level threading APIs do offer a means to forcefully terminate threads, but invariably with the cautionary note that such a function is a blunt tool that should be replaced with a higher-level shutdown protocol.

D offers a simple and robust thread termination protocol. Each thread has an owner thread; by default the owner is the thread that initiated the spawn. You can change the current thread's owner dynamically by calling setOwner(tid). Each thread has exactly one owner but a given thread may own multiple threads.

The most important manifestation of the owner/owned relationship is that when the owner thread terminates, the calls to receive in the owned thread will throw the OwnerTerminated exception. The exception is thrown only if receive has no more matching messages and must wait for a new message; as long as receive has something to fetch from the mailbox, it will not throw. In other words, when the owner thread terminates, the owned threads' calls to receive (or receiveOnly for that matter) will throw OwnerTerminated if and only if they would otherwise block waiting for a new message. The ownership relation is not necessarily unidirectional. In fact, two threads may even own each other; in that case, whichever thread finishes will notify the other.

With thread ownership in mind, let's take a fresh look at the file copy program on page 406. At any given moment, there are a number of messages in flight between the main thread and the secondary thread. The faster the reads are relative to writes, the more buffers will wait in the writer thread's mailbox waiting to be processed. When main returns, it will cause the call to receive to throw an exception, but not before all of the pending messages are handled. Right after the mailbox of the writer is cleared (and the last drop of data is written to the target file), the next call to receive throws. The writer thread exits with the OwnerTerminated exception, which is recognized by the runtime system, which simply ignores it. The operating system closes stdin and stdout as it always does, and the copy operation succeeds.

It may appear there is a race between the moment the last message is sent from main and the moment main returns (causing receive to throw). What if the exception "makes it" before the last message—or worse, before the last few messages? In fact there is no race because causality is always respected in the posting thread: the last message is posted onto the secondary thread's queue before the OwnerTerminated exception makes its way (in fact, propagating the exception is done via the same queue as regular messages). However, a race would exist if main exits while a different, third thread is posting messages onto fileWriter's queue.

A similar reasoning shows that our previous simple example that writes 200 messages in lockstep is also correct: main exits after mailing (in the nick of time) the last message to the secondary thread. The secondary thread first exhausts the queue and then ends with the OwnerTerminated exception.

If you find throwing an exception too harsh a mechanism for handling a thread's exit, you can always handle OwnerTerminated explicitly:

// Ends without an exception
void fileWriter() {
   // Write loop
   for (bool running = true; running; ) {
      receive(
         (immutable(ubyte)[] buffer) { tgt.write(buffer); },
         (OwnerTerminated) { running = false; }
      );
   }
   stderr.writeln("Normally terminated.");
}

In this case, fileWriter returns peacefully when main exits and everyone's happy. But what happens in the case when the secondary thread—the writer—throws an exception? The call to the write function may fail if there's a problem writing data to tgt. In that case, the call to send from the primary thread will fail by throwing an OwnedFailed exception, which is exactly what should happen. By the way, if an owned thread exits normally (as opposed to throwing an exception), subsequent calls to send to that thread also fail, just with a different exception type: OwnedTerminated.

The file copy program is more robust than its simplicity may suggest. However, it should be said that relying on the default termination protocol works smoothly when the relationships between threads are simple and well understood. When there are many participating threads and the ownership graph is complex, it is best to establish explicit "end-of-communication" protocols throughout. In the file copy example, a simple idea would be to send by convention a buffer of size zero to signal the writer that the reading thread has finished successfully. Then the writer acknowledges termination to the reader, which finally can exit. Such an explicit protocol scales well to cases when there are multiple threads processing the data stream between the reader and the writer.

  • + Share This
  • 🔖 Save To Your Account