beetlebug▾
/

thread mutex

Makes, locks, unlocks, and removes the mutexes of the group.

thread::mutex create ?-recursive?
thread::mutex lock MUTEX
thread::mutex unlock MUTEX
thread::mutex destroy MUTEX

Description

The command thread::mutex works on the mutexes of the group. create makes a mutex and gives its handle, such as mid0. lock waits until the calling thread holds the mutex, unlock unlocks it, and destroy removes it. A handle is a name in a table of the group, so a bad name is an error.

An exclusive mutex gives an error when the thread that holds it locks it again. A recursive mutex counts the locks of its thread, and each lock needs its unlock. A lock waits in slices of 50 ms and checks the stop flag of the thread after each one, so a cancel stops a thread that waits. A mutex that a thread holds at its end goes free. A destroy of a mutex that a thread holds is an error.

The handles of thread::mutex, thread::rwmutex, and thread::cond come from one counter of the group.

Arguments

ArgumentTypeDefaultDescription
MUTEXmutex handlerequiredA handle of thread::mutex create.

Options

OptionTypeDefaultDescription
-recursiveflagnoneMakes a mutex that its thread can lock more than once.

-recursive

Makes a mutex that its thread can lock more than once.

The mutex counts the locks of the thread that holds it, and goes free after the same count of unlocks.

% set m [thread::mutex create -recursive]
> thread::mutex lock $m
> thread::mutex lock $m
> thread::mutex unlock $m
> thread::mutex unlock $m
% thread::mutex create -bogus
wrong # args: should be "thread::mutex create ?-recursive?"
-errorcode TCL WRONGARGS

Returns

The handle for create, else an empty string.

Examples

% thread::mutex create
mid0

% set m [thread::mutex create]
> thread::mutex lock $m
> thread::mutex unlock $m
> thread::mutex destroy $m

Errors

% thread::mutex
wrong # args: should be "thread::mutex option ?args?"
-errorcode TCL WRONGARGS

% thread::mutex bogus x
bad option "bogus": must be create, destroy, lock, or unlock
-errorcode NONE

% thread::mutex lock mid99
no such mutex "mid99"
-errorcode NONE

% set m [thread::mutex create]
> thread::mutex lock $m
> thread::mutex lock $m
locking the same exclusive mutex twice from the same thread
-errorcode NONE

% set m [thread::mutex create]
> thread::mutex unlock $m
mutex is not locked
-errorcode NONE

% set m [thread::mutex create]
> set t [thread::create]
> thread::send $t [list thread::mutex lock $m]
> thread::mutex destroy $m
mutex is in use
-errorcode NONE

Facts

Capability
thread. A new interpreter does not have it until the host turns it on.
Tcl release
Tcl 9.1 and 8.6.
Since
ztcl 1.0.0-beta.1

See also