3
votes

In my C++ code, if I create one tcl interp per thread, and use it to Tcl_EvalEx a script, and get result by Tcl_GetStringResult, is this thread safe?

There's no shared data between these threads except const data.

After some searching on google I found this in the tcl threading model doc: http://www.tcl.tk/doc/howto/thread_model.html

Tcl lets you have one or more Tcl interpreters (e.g., created with Tcl_CreateInterp()) in each operating system thread. However, each interpreter is tightly bound to its OS thread and errors will occur if you let more than one thread call into the same interpreter (e.g., with Tcl_Eval).

I guess that means if I don't shared data between interpreters, then there should be no issue?

1

1 Answers

3
votes

I create one tcl interp per thread, and use it to Tcl_EvalEx a script, and get result by Tcl_GetStringResult, is this thread safe?

Yes. Tcl's engine uses thread-specific data extensively, so transferring an interpreter between threads is impossible[*] (things break horribly), but you have the up-side that thread-safety is guaranteed at the same time. The main thing to remember is to use Tcl's built-in memory allocator functions when intermingling with Tcl's implementation at all instead of trying to do it yourself, as one of the key things that threaded Tcl uses is a thread-aware memory allocator (much faster, given that most data stays bound to a single thread).

Simple code can, indeed, stay simple. Nice, yes?


[*] OK, it's possible if you do tricks like building a non-thread-aware version and so on, but it's really tricky and one for deep experts only as the potential for catastrophic problems is really high. Tcl's highly partitioned model is hugely easier to work with.