Threads(3tcl)
π Threads β Tcl thread support π
Threads(3tcl), from the Tcl Library Procedures corner of the world. This is the page where Tcl hands you actual, real, grown-up thread support, and bestie, we're gonna walk through every single bit of it together. No skimming. No skipping. We eat the whole plate. π
β¨ NAME β¨
Tcl_ConditionNotify, Tcl_ConditionWait, Tcl_ConditionFinalize, Tcl_GetThreadData, Tcl_MutexLock, Tcl_MutexUnlock, Tcl_MutexFinalize, Tcl_CreateThread, Tcl_JoinThread β that's the whole squad, and their job is Tcl thread support. π
πΈ SYNOPSIS πΈ
#include <tcl.h>
Tcl_ConditionNotify(condPtr)
Tcl_ConditionWait(condPtr, mutexPtr, timePtr)
Tcl_ConditionFinalize(condPtr)
void *
Tcl_GetThreadData(keyPtr, size)
Tcl_MutexLock(mutexPtr)
Tcl_MutexUnlock(mutexPtr)
Tcl_MutexFinalize(mutexPtr)
int
Tcl_CreateThread(idPtr, proc, clientData, stackSize, flags)
int
Tcl_JoinThread(id, result)
Look at that lineup. π Nine little entry points and every one of them is pulling its weight.
π ARGUMENTS π
Here's who's who at the function party. Pay attention, because these types matter, fr fr.
Tcl_Condition *condPtr(in) β a condition variable, and it has to be associated with a mutex lock. They're a package deal, iykyk.Tcl_Mutex *mutexPtr(in) β a recursive mutex lock.const Tcl_Time *timePtr(in) β a time limit on the condition wait. PassNULLto wait forever, iconic queen behaviour. But heads up: a polling value of0seconds does not make much sense. Like, why. Don't.Tcl_ThreadDataKey *keyPtr(in) β this identifies a block of thread local storage. The key should be static and process-wide</>, but each thread ends up associating a different block of storage with that same key. One key, many lockers. Very main character.int *size(in) β the size of the thread local storage block. This much data gets allocated and initialized to zero the first time each thread callsTcl_GetThreadData. Fresh start, zeroes only. β¨Tcl_ThreadId *idPtr(out) β the referred storage will contain the id of the newly created thread, as returned by the operating system.Tcl_ThreadId id(in) β the id of the thread being waited upon. Patience is a virtue bestie.Tcl_ThreadCreateProc *proc(in) β this procedure acts as themain()of the newly created thread, and the specifiedclientDatawill be its sole argument. It's literally the thread's whole personality.void *clientData(in) β arbitrary information, passed as the sole argument to theproc.size_t stackSize(in) β the size of the stack given to the new thread.int flags(in) β a bitmask containing flags that let the caller modify the behavior of the new thread.int *result(out) β the referred storage is where the exit code of the thread being waited upon gets placed.
π¦ INTRODUCTION π¦
Starting with the 8.1 release, the Tcl core is thread safe. That means you can incorporate Tcl into multithreaded applications without customizing the Tcl core. Slay. No forking the core, no patch chaos, just vibes.
But β and this is the big one, the one you do not forget β an important constraint of the Tcl threads implementation is that only the thread that created a Tcl interpreter can use that interpreter. In other words, multiple threads can not access the same Tcl interpreter. Not a suggestion, not a soft preference, it's the rule.
However! A single thread can safely create and use multiple interpreters. So one thread can hoard as many interpreters as it wants. Greedy but legal. π
π DESCRIPTION π
Tcl provides Tcl_CreateThread for creating threads. The caller can determine the size of the stack given to the new thread and modify the behavior through the supplied flags.
The value TCL_THREAD_STACK_DEFAULT for the stackSize indicates that the default size as specified by the operating system is to be used for the new thread. Let the OS pick, it knows its own body.
As for the flags, currently only the values TCL_THREAD_NOFLAGS and TCL_THREAD_JOINABLE are defined:
TCL_THREAD_NOFLAGSβ invokes the default behavior with no special settings. Chill, unbothered, no notes.TCL_THREAD_JOINABLEβ marks the new thread as joinable. This means another thread can wait for such a marked thread to exit and join it. It's giving "we'll meet up later." π«Ά
Restrictions: On some UNIX systems the pthread-library does not contain the functionality to specify the stack size of a thread. On those systems, the specified value for the stack size is ignored. So don't be shocked when your stackSize gets ghosted. π
Tcl provides the Tcl_ExitThread and Tcl_FinalizeThread functions for terminating threads and invoking optional per-thread exit handlers. See the Tcl_Exit page for more information on these procedures.
The Tcl_JoinThread function is provided to allow threads to wait upon the exit of another thread, which must have been marked as joinable through usage of the TCL_THREAD_JOINABLE flag during its creation via Tcl_CreateThread.
Trying to wait for the exit of a non-joinable thread, or a thread which is already waited upon, will result in an error. Waiting for a joinable thread which already exited is possible β the system will retain the necessary information until after the call toTcl_JoinThread. Which means: not callingTcl_JoinThreadfor a joinable thread will cause a memory leak. Bestie. Please. Call it. π
The Tcl_GetThreadData call returns a pointer to a block of thread-private data. Its argument is a key that is shared by all threads, plus a size for the block of storage. The storage is automatically allocated and initialized to all zeros the first time each thread asks for it. And the storage is automatically deallocated by Tcl_FinalizeThread. So tidy. So organized. πΈ
π₯ SYNCHRONIZATION AND COMMUNICATION π₯
Tcl provides Tcl_ThreadQueueEvent and Tcl_ThreadAlert for handling event queuing in multithreaded applications. See the Notifier manual page for more information on these procedures.
A mutex is a lock that is used to serialize all threads through a piece of code by calling Tcl_MutexLock and Tcl_MutexUnlock. If one thread holds a mutex, any other thread calling Tcl_MutexLock will block until Tcl_MutexUnlock is called. A mutex can be destroyed after its use by calling Tcl_MutexFinalize.
Mutexes are reentrant: they can be locked several times from the same thread. However, there must be exactly one call to Tcl_MutexUnlock for each call to Tcl_MutexLock in order for a thread to release a mutex completely. Count them. Every lock has a matching unlock. It's a situationship with receipts.
The Tcl_MutexLock, Tcl_MutexUnlock and Tcl_MutexFinalize procedures are defined as empty macros if not compiling with threads enabled.
For declaration of mutexes, the TCL_DECLARE_MUTEX macro should be used. This macro assures correct mutex handling even when the core is compiled without threads enabled. It's the responsible friend who makes sure everything still works. π«Ά
A condition variable is used as a signaling mechanism: a thread can lock a mutex and then wait on a condition variable with Tcl_ConditionWait. This atomically releases the mutex lock and blocks the waiting thread until another thread calls Tcl_ConditionNotify.
The caller of Tcl_ConditionNotify should have the associated mutex held by previously calling Tcl_MutexLock β but this is not enforced. Nobody's checking. Be better than nobody.
Notifying the condition variable unblocks all threads waiting on the condition variable, but they do not proceed until the mutex is released with Tcl_MutexUnlock. The implementation of Tcl_ConditionWait automatically locks the mutex before returning. So convenient. β¨
The caller ofTcl_ConditionWaitshould be prepared for spurious notifications by callingTcl_ConditionWaitwithin awhileloop that tests some invariant. Yes, you might get woken up for no reason. It's not you, it's the implementation. Test your invariant, bestie.
A condition variable can be destroyed after its use by calling Tcl_ConditionFinalize.
The Tcl_ConditionNotify, Tcl_ConditionWait and Tcl_ConditionFinalize procedures are defined as empty macros if not compiling with threads enabled.
π INITIALIZATION π
All of these synchronization objects are self-initializing. They are implemented as opaque pointers that should be NULL upon first use.
The mutexes and condition variables are either cleaned up by process exit handlers (if living that long) or explicitly by calls to Tcl_MutexFinalize or Tcl_ConditionFinalize. Thread local storage is reclaimed during Tcl_FinalizeThread.
Self-initializing. Low maintenance. The dream. π
π§ SCRIPT-LEVEL ACCESS TO THREADS π§
Tcl provides no built-in commands for scripts to use to create, manage, or join threads, nor any script-level access to mutex or condition variables. It provides such facilities only via C interfaces, and leaves it up to packages to expose these matters to the script level.
One such package is the Thread package. Go thank it. π
π EXAMPLE π
To create a thread with portable code, its implementation function should be declared as follows:
static Tcl_ThreadCreateProc MyThreadImplFunc;
It should then be defined like this example, which just counts up to a given value and then finishes:
static Tcl_ThreadCreateType
MyThreadImplFunc(
void *clientData)
{
int i, limit = (int) clientData;
for (i=0 ; i<limit ; i++) {
/* doing nothing at all here */
}
TCL_THREAD_CREATE_RETURN;
}
To create the above thread, make it execute, and wait for it to finish, we would do this:
int limit = 1000000000;
void *limitData = (void*)((intptr_t) limit);
Tcl_ThreadId id; /* holds identity of thread created */
int result;
if (Tcl_CreateThread(&id, MyThreadImplFunc, limitData,
TCL_THREAD_STACK_DEFAULT,
TCL_THREAD_JOINABLE) != TCL_OK) {
/* Thread did not create correctly */
return;
}
/* Do something else for a while here */
if (Tcl_JoinThread(id, &result) != TCL_OK) {
/* Thread did not finish properly */
return;
}
/* All cleaned up nicely */
Look at that. Created, executed, joined, cleaned up. The full arc. Ate and left no crumbs. πβ¨
π SEE ALSO π
Tcl_GetCurrentThread(3tcl), Tcl_ThreadQueueEvent(3tcl), Tcl_ThreadAlert(3tcl), Tcl_ExitThread(3tcl), Tcl_FinalizeThread(3tcl), Tcl_CreateThreadExitHandler(3tcl), Tcl_DeleteThreadExitHandler(3tcl), Thread
π KEYWORDS π
thread, mutex, condition variable, thread local storage
And that's the whole page, bestie. Every flag, every macro, every warning about memory leaks and spurious wakeups β it's all here. π¦
This was Tcl 8.1, and this page is Threads(3tcl). Stay thread safe, hold your mutex responsibly, and always, always call Tcl_JoinThread. πππΈ
π¦ where this page comes from
- ubuntu resolute: tcl9.0-doc 9.0.3+dfsg-1
- ubuntu stonking: tcl9.0-doc 9.0.4+dfsg-1
- Copyright (c) 1999 Scriptics Corporation
- Copyright (c) 1998 Sun Microsystems, Inc
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms