1thread(n)                                                            thread(n)
2
3
4
5______________________________________________________________________________
6

NAME

8       thread - Extension for script access to Tcl threading
9

SYNOPSIS

11       package require Tcl  8.4
12
13       package require Thread  ?2.8?
14
15       thread::create ?-joinable? ?-preserved? ?script?
16
17       thread::preserve ?id?
18
19       thread::release ?-wait? ?id?
20
21       thread::id
22
23       thread::errorproc ?procname?
24
25       thread::cancel ?-unwind? id ?result?
26
27       thread::unwind
28
29       thread::exit ?status?
30
31       thread::names
32
33       thread::exists id
34
35       thread::send ?-async? ?-head? id script ?varname?
36
37       thread::broadcast script
38
39       thread::wait
40
41       thread::eval ?-lock mutex? arg ?arg ...?
42
43       thread::join id
44
45       thread::configure id ?option? ?value? ?...?
46
47       thread::transfer id channel
48
49       thread::detach channel
50
51       thread::attach channel
52
53       thread::mutex
54
55       thread::mutex create ?-recursive?
56
57       thread::mutex destroy mutex
58
59       thread::mutex lock mutex
60
61       thread::mutex unlock mutex
62
63       thread::rwmutex
64
65       thread::rwmutex create
66
67       thread::rwmutex destroy mutex
68
69       thread::rwmutex rlock mutex
70
71       thread::rwmutex wlock mutex
72
73       thread::rwmutex unlock mutex
74
75       thread::cond
76
77       thread::cond create
78
79       thread::cond destroy cond
80
81       thread::cond notify cond
82
83       thread::cond wait cond mutex ?ms?
84
85______________________________________________________________________________
86

DESCRIPTION

88       The thread extension creates threads that contain Tcl interpreters, and
89       it lets you send scripts to those threads  for  evaluation.   Addition‐
90       ally,  it  provides script-level access to basic thread synchronization
91       primitives, like mutexes and condition variables.
92

COMMANDS

94       This section describes commands for creating and destroying threads and
95       sending scripts to threads for evaluation.
96
97       thread::create ?-joinable? ?-preserved? ?script?
98              This  command  creates a thread that contains a Tcl interpreter.
99              The Tcl interpreter either evaluates  the  optional  script,  if
100              specified, or it waits in the event loop for scripts that arrive
101              via the thread::send command. Both  of  them  would  take  place
102              simultaneously  with the return of command thread::create to the
103              caller thread.  Neither the caller is waiting for the  finishing
104              of  optional  script,  nor  the result, if any, of the script is
105              returned to the caller.  The result of thread::create is the  ID
106              of  the  thread.  This is the opaque handle which identifies the
107              newly created thread for all other package commands. The  handle
108              of  the  thread  goes  out of scope automatically when thread is
109              marked for exit (see the thread::release command below).
110
111              If the optional script argument contains the  thread::wait  com‐
112              mand  the thread will enter into the event loop. If such command
113              is not found  in the script the thread will run  the  script  to
114              the end and exit. In that case, the handle may be safely ignored
115              since it refers to a thread which does not exists  any  more  at
116              the time when the command returns.
117
118              Using flag -joinable it is possible to create a joinable thread,
119              i.e.  one  upon  whose  exit  can  be  waited  upon   by   using
120              thread::join  command.   Note that failure to join a thread cre‐
121              ated with -joinable flag results in resource and memory leaks.
122
123              Threads created by the thread::create cannot be destroyed force‐
124              fully.  Consequently,  there  is no corresponding thread destroy
125              command. A thread may only be released using the thread::release
126              and if its internal reference count drops to zero, the thread is
127              marked for exit. This kicks the thread out  of  the  event  loop
128              servicing and the thread continues to execute commands passed in
129              the script argument, following the thread::wait command. If this
130              was  the  last  command  in the script, as usually the case, the
131              thread will exit.
132
133              It is possible to create a situation in which it may be impossi‐
134              ble to terminate the thread, for example by putting some endless
135              loop after the thread::wait or entering the event loop again  by
136              doing  an  vwait-type  of command. In such cases, the thread may
137              never exit. This is considered to be a bad practice  and  should
138              be  avoided if possible. This is best illustrated by the example
139              below:
140
141
142                  # You should never do ...
143                  set tid [thread::create {
144                      package require Http
145                      thread::wait
146                      vwait forever ; # <-- this!
147                  }]
148
149
150              The thread created in the above example will never  be  able  to
151              exit.   After  it  has  been  released  with  the  last matching
152              thread::release  call,  the  thread  will  jump   out   of   the
153              thread::wait and continue to execute commands following. It will
154              enter vwait command and wait endlessly for events. There  is  no
155              way  one  can  terminate such thread, so you wouldn't want to do
156              this!
157
158              Each newly created has its internal reference counter set  to  0
159              (zero),  i.e. it is unreserved. This counter gets incremented by
160              a  call  to  thread::preserve  and  decremented  by  a  call  to
161              thread::release command. These two commands implement simple but
162              effective thread reservation system and  offer  predictable  and
163              controllable thread termination capabilities. It is however pos‐
164              sible to create initially preserved threads by using flag  -pre‐
165              served  of the thread::create command. Threads created with this
166              flag have the initial value of the reference counter of 1 (one),
167              and are thus initially marked reserved.
168
169       thread::preserve ?id?
170              This  command increments the thread reference counter. Each call
171              to this command increments the reference  counter  by  one  (1).
172              Command  returns  the  value  of the reference counter after the
173              increment.  If called with the optional thread id,  the  command
174              preserves the given thread. Otherwise the current thread is pre‐
175              served.
176
177              With reference counting, one can implement controlled access  to
178              a  shared Tcl thread. By incrementing the reference counter, the
179              caller signalizes that he/she wishes to use  the  thread  for  a
180              longer  period of time. By decrementing the counter, caller sig‐
181              nalizes that he/she has finished using the thread.
182
183       thread::release ?-wait? ?id?
184              This command decrements the thread reference counter. Each  call
185              to this command decrements the reference counter by one (1).  If
186              called with the optional thread id,  the  command  releases  the
187              given  thread.  Otherwise, the current thread is released.  Com‐
188              mand returns the value of the reference counter after the decre‐
189              ment.   When  the reference counter reaches zero (0), the target
190              thread is marked for termination. You should not  reference  the
191              thread  after  the thread::release command returns zero or nega‐
192              tive integer.  The handle of the thread goes out  of  scope  and
193              should not be used any more. Any following reference to the same
194              thread handle will result in Tcl error.
195
196              Optional flag -wait instructs the caller thread to wait for  the
197              target thread to exit, if the effect of the command would result
198              in termination of the target thread, i.e. if the  return  result
199              would  be zero (0). Without the flag, the caller thread does not
200              wait for the target thread to exit.  Care  must  be  taken  when
201              using  the -wait, since this may block the caller thread indefi‐
202              nitely.  This option has been implemented for some special  uses
203              of  the  extension  and  is  deprecated for regular use. Regular
204              users should create joinable  threads  by  using  the  -joinable
205              option  of  the  thread::create  command and the thread::join to
206              wait for thread to exit.
207
208       thread::id
209              This command returns the ID of the current thread.
210
211       thread::errorproc ?procname?
212              This command sets a handler for errors  that  occur  in  scripts
213              sent  asynchronously,  using the -async flag of the thread::send
214              command, to other threads. If no handler is specified, the  cur‐
215              rent handler is returned. The empty string resets the handler to
216              default (unspecified) value.  An  uncaught  error  in  a  thread
217              causes  an  error message to be sent to the standard error chan‐
218              nel. This default reporting scheme can be changed by registering
219              a procedure which is called to report the error. The procname is
220              called in the interpreter  that  invoked  the  thread::errorproc
221              command. The procname is called like this:
222
223
224                  myerrorproc thread_id errorInfo
225
226
227       thread::cancel ?-unwind? id ?result?
228              This command requires Tcl version 8.6 or higher.
229
230              Cancels the script being evaluated in the thread given by the id
231              parameter. Without the -unwind switch the evaluation  stack  for
232              the  interpreter  is unwound until an enclosing catch command is
233              found or there are no further  invocations  of  the  interpreter
234              left  on  the call stack. With the -unwind switch the evaluation
235              stack for the interpreter  is  unwound  without  regard  to  any
236              intervening catch command until there are no further invocations
237              of the interpreter left on the call stack. If result is present,
238              it  will  be  used  as  the  error  message string; otherwise, a
239              default error message string will be used.
240
241       thread::unwind
242              Use of this command is deprecated in  favour  of  more  advanced
243              thread  reservation system implemented with thread::preserve and
244              thread::release commands.  Support  for  thread::unwind  command
245              will disappear in some future major release of the extension.
246
247              This  command  stops  a prior thread::wait command. Execution of
248              the script passed to newly created thread will continue from the
249              thread::wait  command.  If  thread::wait was the last command in
250              the script, the thread will  exit.  The  command  returns  empty
251              result but may trigger Tcl error with the message "target thread
252              died" in some situations.
253
254       thread::exit ?status?
255              Use of this command is deprecated in  favour  of  more  advanced
256              thread  reservation system implemented with thread::preserve and
257              thread::release commands. Support for thread::exit command  will
258              disappear in some future major release of the extension.
259
260              This  command  forces a thread stuck in the thread::wait command
261              to unconditionally exit. The thread's exit  status  defaults  to
262              666 and can be specified using the optional status argument. The
263              execution of thread::exit command is  guaranteed  to  leave  the
264              program  memory  in the inconsistent state, produce memory leaks
265              and otherwise affect other subsystem(s) of the  Tcl  application
266              in an unpredictable manner. The command returns empty result but
267              may trigger Tcl error with the message "target thread  died"  in
268              some situations.
269
270       thread::names
271              This  command  returns  a list of thread IDs. These are only for
272              threads that have been created via thread::create  command.   If
273              your  application creates other threads at the C level, they are
274              not reported by this command.
275
276       thread::exists id
277              Returns true (1) if thread given by  the  id  parameter  exists,
278              false  (0)  otherwise.  This  applies only for threads that have
279              been created via thread::create command.
280
281       thread::send ?-async? ?-head? id script ?varname?
282              This command passes a script to another thread and,  optionally,
283              waits  for the result. If the -async flag is specified, the com‐
284              mand does not wait for the result and it returns  empty  string.
285              The target thread must enter it's event loop in order to receive
286              scripts sent via this command.  This  is  done  by  default  for
287              threads  created without a startup script. Threads can enter the
288              event loop explicitly by calling thread::wait or any other rele‐
289              vant Tcl/Tk command, like update, vwait, etc.
290
291              Optional  varname  specifies  name  of the variable to store the
292              result of the script.  Without  the  -async  flag,  the  command
293              returns the evaluation code, similarly to the standard Tcl catch
294              command. If, however, the -async flag is specified, the  command
295              returns  immediately  and caller can later vwait on ?varname? to
296              get the result of the passed script
297
298
299                  set t1 [thread::create]
300                  set t2 [thread::create]
301                  thread::send -async $t1 "set a 1" result
302                  thread::send -async $t2 "set b 2" result
303                  for {set i 0} {$i < 2} {incr i} {
304                      vwait result
305                  }
306
307
308              In the above example, two threads were fed work and both of them
309              were  instructed  to signalize the same variable "result" in the
310              calling thread.  The caller entered the event loop twice to  get
311              both  results.  Note,  however,  that  the order of the received
312              results may vary, depending on the current system load, type  of
313              work done, etc, etc.
314
315              Many  threads  can  simultaneously  send  scripts  to the target
316              thread for execution. All of them are  entered  into  the  event
317              queue  of  the  target  thread  and  executed on the FIFO basis,
318              intermingled with optional other events  pending  in  the  event
319              queue  of the target thread.  Using the optional ?-head? switch,
320              scripts posted to the thread's event queue can be placed on  the
321              head,  instead  on the tail of the queue, thus being executed in
322              the LIFO fashion.
323
324       thread::broadcast script
325              This command passes a script to all threads created by the pack‐
326              age for execution. It does not wait for response from any of the
327              threads.
328
329       thread::wait
330              This enters the event loop so a thread can receive messages from
331              the  thread::send  command.  This  command  should  only be used
332              within the script passed to the thread::create. It should be the
333              very  last  command  in the script. If this is not the case, the
334              exiting thread will continue executing the script lines past the
335              thread::wait which is usually not what you want and/or expect.
336
337
338                  set t1 [thread::create {
339                      #
340                      # Do some initialization work here
341                      #
342                      thread::wait ; # Enter the event loop
343                  }]
344
345
346       thread::eval ?-lock mutex? arg ?arg ...?
347              This  command  concatenates  passed  arguments and evaluates the
348              resulting script under the mutex  protection.  If  no  mutex  is
349              specified  by  using  the  ?-lock  mutex? optional argument, the
350              internal static mutex is used.
351
352       thread::join id
353              This command waits for the thread with ID id to  exit  and  then
354              returns  it's  exit  code.  Errors  will be returned for threads
355              which are not joinable or already waited upon by another thread.
356              Upon the join the handle of the thread has gone out of scope and
357              should not be used any more.
358
359       thread::configure id ?option? ?value? ?...?
360              This command configures various low-level aspects of the  thread
361              with  ID id in the similar way as the standard Tcl command fcon‐
362              figure configures some Tcl channel  options.  Options  currently
363              supported are: -eventmark and -unwindonerror.
364
365              When  -eventmark is provided with a value greater than 0 (zero),
366              that value  is  the  maximum  number  of  asynchronously  posted
367              scripts that may be pending for the thread.  thread::send -async
368              blocks until the number of pending scripts  in  the  event  loop
369              drops below the -eventmark value.
370
371              When  -unwindonerror  is provided with a value of true, an error
372              result in a script  causes  the  thread  to  unwind,  making  it
373              unavailable to evaluate additional scripts.
374
375       thread::transfer id channel
376              This  moves  the  specified  channel from the current thread and
377              interpreter to the main interpreter of the thread with the given
378              id.  After the move the current interpreter has no access to the
379              channel any more, but the main interpreter of the target  thread
380              will be able to use it from now on.  The command waits until the
381              other thread has incorporated the channel. Because of this it is
382              possible to deadlock the participating threads by commanding the
383              other through a synchronous thread::send to transfer  a  channel
384              to us.  This easily extends into longer loops of threads waiting
385              for each other. Other restrictions: the channel in question must
386              not be shared among multiple interpreters running in the sending
387              thread. This automatically excludes  the  special  channels  for
388              standard input, output and error.
389
390              Due  to the internal Tcl core implementation and the restriction
391              on transferring shared channels, one has to take extra  measures
392              when  transferring socket channels created by accepting the con‐
393              nection out of the socket commands callback procedures:
394
395
396                  socket -server _Accept 2200
397                  proc _Accept {s ipaddr port} {
398                      after idle [list Accept $s $ipaddr $port]
399                  }
400                  proc Accept {s ipaddr port} {
401                      set tid [thread::create]
402                      thread::transfer $tid $s
403                  }
404
405
406       thread::detach channel
407              This detaches the specified channel from the current thread  and
408              interpreter.  After  that, the current interpreter has no access
409              to the channel any more. The channel  is  in  the  parked  state
410              until some other (or the same) thread attaches the channel again
411              with thread::attach.  Restrictions:  same  as  for  transferring
412              shared channels with the thread::transfer command.
413
414       thread::attach channel
415              This  attaches  the  previously  detached channel in the current
416              thread/interpreter. For already existing channels,  the  command
417              does nothing, i.e. it is not an error to attach the same channel
418              more than once. The first operation will  actually  perform  the
419              operation,  while all subsequent operation will just do nothing.
420              Command throws error if the channel cannot be found in the  list
421              of detached channels and/or in the current interpreter.
422
423       thread::mutex
424              Mutexes are most common thread synchronization primitives.  They
425              are used to synchronize access from two or more threads  to  one
426              or  more  shared  resources.  This command provides script-level
427              access to exclusive and/or recursive mutexes. Exclusive  mutexes
428              can  be  locked only once by one thread, while recursive mutexes
429              can be locked many times  by  the  same  thread.  For  recursive
430              mutexes, number of lock and unlock operations must match, other‐
431              wise, the mutex will never be released, which would lead to var‐
432              ious deadlock situations.
433
434              Care  has  to  be  taken when using mutexes in an multithreading
435              program.  Improper use of mutexes may lead to  various  deadlock
436              situations, especially when using exclusive mutexes.
437
438              The  thread::mutex  command  supports  following subcommands and
439              options:
440
441              thread::mutex create ?-recursive?
442                     Creates the mutex and returns it's  opaque  handle.  This
443                     handle  should  be  used  for any future reference to the
444                     newly created mutex.  If no optional  ?-recursive?  argu‐
445                     ment  was  specified,  the  command creates the exclusive
446                     mutex. With the ?-recursive? argument, the  command  cre‐
447                     ates a recursive mutex.
448
449              thread::mutex destroy mutex
450                     Destroys  the  mutex.  Mutex  should be in unlocked state
451                     before the destroy attempt. If the mutex is  locked,  the
452                     command will throw Tcl error.
453
454              thread::mutex lock mutex
455                     Locks  the  mutex.  Locking the exclusive mutex may throw
456                     Tcl error if on attempt to lock the same mutex twice from
457                     the same thread. If your program logic forces you to lock
458                     the same mutex twice or more from the same  thread  (this
459                     may happen in recursive procedure invocations) you should
460                     consider using the recursive mutexes.
461
462              thread::mutex unlock mutex
463                     Unlocks the mutex so some other thread may lock it again.
464                     Attempt  to  unlock the already unlocked mutex will throw
465                     Tcl error.
466
467
468       thread::rwmutex
469              This   command   creates   many-readers/single-writer   mutexes.
470              Reader/writer  mutexes allow you to serialize access to a shared
471              resource more optimally.  In situations where a shared  resource
472              gets  mostly  read and seldom modified, you might gain some per‐
473              formance by using reader/writer mutexes instead of exclusive  or
474              recursive mutexes.
475
476              For  reading  the  resource, thread should obtain a read lock on
477              the resource.  Read lock is  non-exclusive,  meaning  that  more
478              than  one  thread  can  obtain a read lock to the same resource,
479              without waiting on other readers.  For  changing  the  resource,
480              however,  a thread must obtain a exclusive write lock. This lock
481              effectively blocks all threads from gaining the read-lock  while
482              the  resource is been modified by the writer thread.  Only after
483              the write lock has been released,  the  resource  may  be  read-
484              locked again.
485
486              The  thread::rwmutex  command supports following subcommands and
487              options:
488
489              thread::rwmutex create
490                     Creates the reader/writer mutex and returns  it's  opaque
491                     handle.  This handle should be used for any future refer‐
492                     ence to the newly created mutex.
493
494              thread::rwmutex destroy mutex
495                     Destroys the reader/writer mutex. If the mutex is already
496                     locked, attempt to destroy it will throw Tcl error.
497
498              thread::rwmutex rlock mutex
499                     Locks  the  mutex  for  reading. More than one thread may
500                     read-lock the same mutex at the same time.
501
502              thread::rwmutex wlock mutex
503                     Locks the mutex for writing. Only one thread  may  write-
504                     lock  the  same mutex at the same time. Attempt to write-
505                     lock same mutex twice from the same thread will throw Tcl
506                     error.
507
508              thread::rwmutex unlock mutex
509                     Unlocks the mutex so some other thread may lock it again.
510                     Attempt to unlock already unlocked mutex will  throw  Tcl
511                     error.
512
513
514       thread::cond
515              This  command  provides  script-level  access to condition vari‐
516              ables.  A condition variable creates a safe environment for  the
517              program  to  test  some condition, sleep on it when false and be
518              awakened when it might have become true. A condition variable is
519              always  used  in the conjunction with an exclusive mutex. If you
520              attempt to use other type of mutex in conjunction with the  con‐
521              dition variable, a Tcl error will be thrown.
522
523              The command supports following subcommands and options:
524
525              thread::cond create
526                     Creates  the  condition  variable and returns it's opaque
527                     handle.  This handle should be used for any future refer‐
528                     ence to newly created condition variable.
529
530              thread::cond destroy cond
531                     Destroys  condition variable cond. Extreme care has to be
532                     taken that nobody is using (i.e. waiting on)  the  condi‐
533                     tion variable, otherwise unexpected errors may happen.
534
535              thread::cond notify cond
536                     Wakes  up  all  threads waiting on the condition variable
537                     cond.
538
539              thread::cond wait cond mutex ?ms?
540                     This command is used to suspend program  execution  until
541                     the  condition  variable  cond  has been signalled or the
542                     optional timer has expired.  The exclusive mutex must  be
543                     locked by the calling thread on entrance to this command.
544                     If the mutex is not locked, Tcl error is  thrown.   While
545                     waiting  on the cond, the command releases mutex.  Before
546                     returning to the calling thread, the command  re-acquires
547                     the  mutex  again. Unlocking the mutex and waiting on the
548                     condition variable cond is done atomically.
549
550                     The ms command option, if given, must be an integer spec‐
551                     ifying time interval in milliseconds the command waits to
552                     be signalled.  Otherwise the command waits  on  condition
553                     notify forever.
554
555                     In  multithreading  programs,  there  are many situations
556                     where a thread has to wait for some event to happen until
557                     it  is  allowed to proceed.  This is usually accomplished
558                     by repeatedly testing a condition under the mutex protec‐
559                     tion and waiting on the condition variable until the con‐
560                     dition evaluates to true:
561
562
563                         set mutex [thread::mutex create]
564                         set cond  [thread::cond  create]
565
566                         thread::mutex lock $mutex
567                         while {<some_condition_is_true>} {
568                             thread::cond wait $cond $mutex
569                         }
570                         # Do some work under mutex protection
571                         thread::mutex unlock $mutex
572
573
574                     Repeated testing of the condition  is  needed  since  the
575                     condition  variable  may get signalled without the condi‐
576                     tion being actually changed  (spurious  thread  wake-ups,
577                     for example).
578

DISCUSSION

580       The fundamental threading model in Tcl is that there can be one or more
581       Tcl interpreters per thread, but each Tcl interpreter  should  only  be
582       used  by  a single thread which created it.  A "shared memory" abstrac‐
583       tion is awkward to provide in Tcl because Tcl makes  assumptions  about
584       variable and data ownership. Therefore this extension supports a simple
585       form of threading where the main thread can manage several  background,
586       or  "worker"  threads.   For  example,  an event-driven server can pass
587       requests to worker  threads,  and  then  await  responses  from  worker
588       threads  or new client requests. Everything goes through the common Tcl
589       event loop, so message passing between  threads  works  naturally  with
590       event-driven I/O, vwait on variables, and so forth. For the transfer of
591       bulk information it is possible to move channels between the threads.
592
593       For advanced multithreading scripts, script-level access to  two  basic
594       synchronization primitives, mutex and condition variables, is also sup‐
595       ported.
596

SEE ALSO

598       http://www.tcl.tk/doc/howto/thread_model.html, tpool, tsv, ttrace
599

KEYWORDS

601       events, message passing, mutex, synchronization, thread
602
603
604
605Tcl Threading                         2.8                            thread(n)
Impressum