Dabo
Dabo

Reputation: 381

How do I write an asynchronous C extension to Tcl?

I have a C function that I'd like to make available to Tcl. The thing is, I'd like to make the call asynchronous from Tcl in the same fashion as ::thread::send, i.e. with ?-async? and ?varname? flags.

I do not understand Tcl's asynchronous C API, and cannot find any examples for how to use it. On the C side, I can create a thread to do the work, but then do not know how to signal when the thread is finished, and how to handle the signal to set the variable specified by the varname option passed in the Tcl command.

For this problem, I am not able to use a simpler asynchronous solution from the Tcl side, such as invoking another process with a pipe, Tcl threads, or a library such as comm. The reason for this is that the C call loads in a large data structure, and there are other C calls exposed to Tcl which assume (out of necessity) that the memory for the structure was allocated within the same thread as the Tcl interp.

Any assistance at all will be much appreciated.

Upvotes: 1

Views: 238

Answers (2)

Donal Fellows
Donal Fellows

Reputation: 137557

The easiest way is write your C code to be synchronous with a simple API, and to keep all its state in ClientData-casted structures attached to commands or an interpreter, if possible, or failing that, using thread-specific data. Then, use the Thread package itself to allow other threads to call these utility threads, and wrap that inside Tcl code that makes the API seem natural and which (lightly) conceals just how you go about implementing the API. Which is pretty easy to do.

You could also use Tcl's C level thread API as the Thread package is really just a wrapper around that. (It actually communicates by sending events between threads; check out the definition of ThreadSend in the Thread package for the gory details.) Or, if you're really doing just I/O, you could write your code to use asynchronous I/O and the fileevent/notifier mechanism. These are rather more complicated than just doing things the simple way outlined above and using Tcl code and existing packages to do much of the work.

Upvotes: 1

Roberto Reale
Roberto Reale

Reputation: 4317

You will need to use the TCL Extension Architecture, a.k.a. TEA.

Upvotes: 0

Related Questions