Updated 2012-06-02 18:10:43 by RLE

In Tcl-land, we often discourage use of threads, for reasons documented elsewhere [explain]. Here's an example of how to think about design involving threads:

Briefly, Tcl applications need threads when they rely on long-running external resources, like database look-up or communications with physical devices [references]. Even in the latter case, though, there are a number of alternatives:

[Use of dqkit as a great convenience.]

[rfoxmich] (and SO and CL) say(s): "... timeouts belong inside the extension that interfaces with the hardware itself."

SG Sep 07 2006: I think that the advice to avoid threads is overstated. Understandable, but overstated. Tcl's thread implementation is actually quite nice and threads coexist rather well with event-driven programs in that inter-thread communication *is* an event.

The rule of thumb I've developed is if you have when you have multiple (largely) orthogonal event sources *and* you would have to re-write code to enable event processing to occur in a timely fashion then you have a good candidate for threads.

Threads let you code at a higher level of granularity and let the OS be responsible for time sharing. It's much easier than trying to break your code down into smaller blocks that are strung together via the event loop if that's not the natural way of expressing it. And (IMO) thread::launch/thread::send is a much cleaner way of interacting than bgexec and pipes and whatnot.

I avoided Tcl's threads for a long time but since I started using it, I think it ought to be promoted more. Not for everything (and threads are often overused) but there are a class of problems that threads provide a clean solution for. A hardware controller is often one of those problems.

PS Jan 13 2009: I have bounced the idea of using threads around. My biggest problem at the moment is that I want to be able to wrap the final application into an EXE. Currently i'm using the starkit method for this which works well but it seems there's not a good option to use this with Threads. Please correct me if I'm wrong.

My main problem is that I am controlling external hardware where I need to keep a timing loop accurate. (Need to execute external hardware events every x milliseconds with an accuracy of +/- 10ms or better). I have a full GUI as well and this application works, but it's a bit finicky. I'm sure I could do more with the event loop but some timed events need to be more precise than that gives me. If I had threads I could keep the timing loop in a thread, the communication interface in a thread, and the GUI in a final thread. This would also likely solve my problem that while dragging a window my code stops executing. (Held up by the event loop?)