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

DISCUSSION

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

SEE ALSO

600       http://www.tcl.tk/doc/howto/thread_model.html, tpool, tsv, ttrace
601

KEYWORDS

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