Updated 2015-04-12 15:08:44 by pooryorick

Purpose: a place to share your wisdom, confusion, hard won knowledge, ... regarding the use of Tcl and threads.

What are threads?

AMG: Threads can be seen as multiple processes with combined state. A threaded programmer's foremost concern should be keeping threads from stomping on each other and corrupting variables, etc. that other threads assumed they had sole control over. Typically very little is thread-local, but Tcl's a tad different because it uses the apartment model, and nearly everything in your thread's interpreter(s) is (are) thread local. But there are exceptions; some program state is shared between all threads.

  • [pwd] is common. Therefore, any thread can at any moment break any other thread that assumes to be in a given working directory. Beware relative paths, or avoid [cd]. Are there any packages or extensions that use [cd]?
  • What else? Please add to this list.

How are threads in Tcl different than people expect?

AMG: One way Tcl threads are different is that no interpreter can have more than one thread. Therefore one thread can't fiddle with variables another thread is assuming it controls. If you want shared variables, you must do so through mechanisms provided by the Thread extension. That's good. But consider that it makes Tcl threads little different from separate processes, so why not just use separate processes?

PYK 2015-03-26: So that you can take advantage of shared memory?

How do I tell if I can use threads in Tcl?

Before being able to use threads in Tcl, you have to specifically specify a configuration time flag. The default is to not build with threads. Unfortunately, the last I checked, the configuration with the thread flags built libraries and executables with the same name as configuring without the flag; this means that you cannot tell simply by file names whether your Tcl has threads or not.

You can tell if your Tcl interpreter has been compiled with threads with the following code:
# Check for threaded Tcl
proc is_threaded {} {
    expr {[info exists ::tcl_platform(threaded)] && $::tcl_platform(threaded)}

Garynkill: With this code, i tried i gotton no results, does it mean i my tcl package doesn't support threading?

If I build Tcl with threads, will I be able to use other extensions?

AMG: Probably, but some (many? most?) extensions aren't thread safe. Such extensions typically aren't safe for use with multiple interps either, since in Tcl threads and interps have much in common.

DKF: The usual suspects are those extensions that use POSIX signals or fork() without an immediately following exec(). So, that's Expect (for Unix) and parts of TclX.