OSDN Git Service

Please enter the commit message for your changes. Lines starting
[eos/base.git] / util / src / TclTk / tcl8.6.12 / pkgs / thread2.8.7 / doc / thread.man
1 [comment {-*- tcl -*- doctools manpage}]
2 [manpage_begin thread n 2.8]
3 [moddesc {Tcl Threading}]
4 [titledesc {Extension for script access to Tcl threading}]
5 [require Tcl 8.4]
6 [require Thread [opt 2.8]]
7
8 [description]
9 The [package thread] extension creates threads that contain Tcl
10 interpreters, and it lets you send scripts to those threads for
11 evaluation.
12
13 Additionally, it provides script-level access to basic thread
14 synchronization primitives, like mutexes and condition variables.
15
16 [section COMMANDS]
17 This section describes commands for creating and destroying threads
18 and sending scripts to threads for evaluation.
19
20
21
22 [list_begin definitions]
23
24 [call [cmd thread::create] [opt -joinable] [opt -preserved] [opt script]]
25
26 This command creates a thread that contains a Tcl interpreter.
27 The Tcl interpreter either evaluates the optional [option script], if
28 specified, or it waits in the event loop for scripts that arrive via
29 the [cmd thread::send] command. The result, if any, of the
30 optional [option script] is never returned to the caller.
31 The result of [cmd thread::create] is the ID of the thread. This is
32 the opaque handle which identifies the newly created thread for
33 all other package commands. The handle of the thread goes out of scope
34 automatically when thread is marked for exit
35 (see the [cmd thread::release] command below).
36
37 [para]
38
39 If the optional [option script] argument contains the [cmd thread::wait]
40 command the thread will enter into the event loop. If such command is not
41 found  in the [option script] the thread will run the [option script] to
42 the end and exit. In that case, the handle may be safely ignored since it
43 refers to a thread which does not exists any more at the time when the
44 command returns.
45
46 [para]
47
48 Using flag [option -joinable] it is possible to create a joinable
49 thread, i.e. one upon whose exit can be waited upon by using
50 [cmd thread::join] command.
51 Note that failure to join a thread created with [option -joinable] flag
52 results in resource and memory leaks.
53
54
55 [para]
56
57 Threads created by the [cmd thread::create] cannot be destroyed
58 forcefully. Consequently, there is no corresponding thread destroy
59 command. A thread may only be released using the [cmd thread::release]
60 and if its internal reference count drops to zero, the thread is
61 marked for exit. This kicks the thread out of the event loop
62 servicing and the thread continues to execute commands passed in
63 the [option script] argument, following the [cmd thread::wait]
64 command. If this was the last command in the script, as usually the
65 case, the thread will exit.
66
67 [para]
68
69 It is possible to create a situation in which it may be impossible
70 to terminate the thread, for example by putting some endless loop
71 after the [cmd thread::wait] or entering the event loop again by
72 doing an vwait-type of command. In such cases, the thread may never
73 exit. This is considered to be a bad practice and should be avoided
74 if possible. This is best illustrated by the example below:
75
76 [example {
77     # You should never do ...
78     set tid [thread::create {
79         package require Http
80         thread::wait
81         vwait forever ; # <-- this!
82     }]
83 }]
84
85 The thread created in the above example will never be able to exit.
86 After it has been released with the last matching [cmd thread::release]
87 call, the thread will jump out of the [cmd thread::wait] and continue
88 to execute commands following. It will enter [cmd vwait] command and
89 wait endlessly for events. There is no way one can terminate such thread,
90 so you wouldn't want to do this!
91
92 [para]
93
94 Each newly created has its internal reference counter set to 0 (zero),
95 i.e. it is unreserved. This counter gets incremented by a call to
96 [cmd thread::preserve] and decremented by a call to [cmd thread::release]
97 command. These two commands implement simple but effective thread
98 reservation system and offer predictable and controllable thread
99 termination capabilities. It is however possible to create initially
100 preserved threads by using flag [option -preserved] of the
101 [cmd thread::create] command. Threads created with this flag have the
102 initial value of the reference counter of 1 (one), and are thus
103 initially marked reserved.
104
105
106 [call [cmd thread::preserve] [opt id]]
107
108 This command increments the thread reference counter. Each call
109 to this command increments the reference counter by one (1).
110 Command returns the value of the reference counter after the increment.
111 If called with the optional thread [option id], the command preserves
112 the given thread. Otherwise the current thread is preserved.
113
114 [para]
115
116 With reference counting, one can implement controlled access to a
117 shared Tcl thread. By incrementing the reference counter, the
118 caller signalizes that he/she wishes to use the thread for a longer
119 period of time. By decrementing the counter, caller signalizes that
120 he/she has finished using the thread.
121
122 [call [cmd thread::release] [opt -wait] [opt id]]
123
124 This command decrements the thread reference counter. Each call to
125 this command decrements the reference counter by one (1).
126 If called with the optional thread [option id], the command releases
127 the given thread. Otherwise, the current thread is released.
128 Command returns the value of the reference counter after the decrement.
129 When the reference counter reaches zero (0), the target thread is
130 marked for termination. You should not reference the thread after the
131 [cmd thread::release] command returns zero or negative integer.
132 The handle of the thread goes out of scope and should not be used any
133 more. Any following reference to the same thread handle will result
134 in Tcl error.
135
136 [para]
137
138 Optional flag [option -wait] instructs the caller thread to wait for
139 the target thread to exit, if the effect of the command would result
140 in termination of the target thread, i.e. if the return result would
141 be zero (0). Without the flag, the caller thread does not wait for
142 the target thread to exit. Care must be taken when using the
143 [option -wait], since this may block the caller thread indefinitely.
144 This option has been implemented for some special uses of the extension
145 and is deprecated for regular use. Regular users should create joinable
146 threads by using the [option -joinable] option of the [cmd thread::create]
147 command and the [cmd thread::join] to wait for thread to exit.
148
149 [call [cmd thread::id]]
150
151 This command returns the ID of the current thread.
152
153 [call [cmd thread::errorproc] [opt procname]]
154
155 This command sets a handler for errors that occur in scripts sent
156 asynchronously, using the [option -async] flag of the
157 [cmd thread::send] command, to other threads. If no handler
158 is specified, the current handler is returned. The empty string
159 resets the handler to default (unspecified) value.
160 An uncaught error in a thread causes an error message to be sent
161 to the standard error channel. This default reporting scheme can
162 be changed by registering a procedure which is called to report
163 the error. The [arg procname] is called in the interpreter that
164 invoked the [cmd thread::errorproc] command. The [arg procname]
165 is called like this:
166
167 [example {
168     myerrorproc thread_id errorInfo
169 }]
170
171 [call [cmd thread::cancel] [opt -unwind] [arg id] [opt result]]
172
173 This command requires Tcl version 8.6 or higher.
174
175 [para]
176
177 Cancels the script being evaluated in the thread given by the [arg id]
178 parameter. Without the [option -unwind] switch the evaluation stack for
179 the interpreter is unwound until an enclosing catch command is found or
180 there are no further invocations of the interpreter left on the call
181 stack. With the [option -unwind] switch the evaluation stack for the
182 interpreter is unwound without regard to any intervening catch command
183 until there are no further invocations of the interpreter left on the
184 call stack. If [arg result] is present, it will be used as the error
185 message string; otherwise, a default error message string will be used.
186
187 [call [cmd thread::unwind]]
188
189 Use of this command is deprecated in favour of more advanced thread
190 reservation system implemented with [cmd thread::preserve] and
191 [cmd thread::release] commands. Support for [cmd thread::unwind]
192 command will disappear in some future major release of the extension.
193 [para]
194 This command stops a prior [cmd thread::wait] command. Execution of
195 the script passed to newly created thread will continue from the
196 [cmd thread::wait] command. If [cmd thread::wait] was the last command
197 in the script, the thread will exit. The command returns empty result
198 but may trigger Tcl error with the message "target thread died" in some
199 situations.
200
201
202 [call [cmd thread::exit] [opt status]]
203
204 Use of this command is deprecated in favour of more advanced thread
205 reservation system implemented with [cmd thread::preserve] and
206 [cmd thread::release] commands. Support for [cmd thread::exit]
207 command will disappear in some future major release of the extension.
208 [para]
209 This command forces a thread stuck in the [cmd thread::wait] command to
210 unconditionally exit. The thread's exit status defaults to 666 and can be
211 specified using the optional [arg status] argument. The execution of
212 [cmd thread::exit] command is guaranteed to leave the program memory in the
213 inconsistent state, produce memory leaks and otherwise affect other subsystem(s)
214 of the Tcl application in an unpredictable manner. The command returns empty
215 result but may trigger Tcl error with the message "target thread died" in some
216 situations.
217
218 [call [cmd thread::names]]
219
220 This command returns a list of thread IDs. These are only for
221 threads that have been created via [cmd thread::create] command.
222 If your application creates other threads at the C level, they
223 are not reported by this command.
224
225
226 [call [cmd thread::exists] [arg id]]
227
228 Returns true (1) if thread given by the [arg id] parameter exists,
229 false (0) otherwise. This applies only for threads that have
230 been created via [cmd thread::create] command.
231
232
233 [call [cmd thread::send] [opt -async] [opt -head] [arg id] [arg script] [opt varname]]
234
235 This command passes a [arg script] to another thread and, optionally,
236 waits for the result. If the [option -async] flag is specified, the
237 command does not wait for the result and it returns empty string.
238 The target thread must enter it's event loop in order to receive
239 scripts sent via this command. This is done by default for threads
240 created without a startup script. Threads can enter the event loop
241 explicitly by calling [cmd thread::wait] or any other relevant Tcl/Tk
242 command, like [cmd update], [cmd vwait], etc.
243
244 [para]
245
246 Optional [option varname] specifies name of the variable to store
247 the result of the [arg script]. Without the [option -async] flag,
248 the command returns the evaluation code, similarly to the standard
249 Tcl [cmd catch] command. If, however, the [option -async] flag is
250 specified, the command returns immediately and caller can later
251 [cmd vwait] on [opt varname] to get the result of the passed [arg script]
252
253 [example {
254     set t1 [thread::create]
255     set t2 [thread::create]
256     thread::send -async $t1 "set a 1" result
257     thread::send -async $t2 "set b 2" result
258     for {set i 0} {$i < 2} {incr i} {
259         vwait result
260     }
261 }]
262
263 In the above example, two threads were fed work and both of them were
264 instructed to signalize the same variable "result" in the calling thread.
265 The caller entered the event loop twice to get both results. Note,
266 however, that the order of the received results may vary, depending on
267 the current system load, type of work done, etc, etc.
268
269 [para]
270
271 Many threads can simultaneously send scripts to the target thread for
272 execution. All of them are entered into the event queue of the target
273 thread and executed on the FIFO basis, intermingled with optional other
274 events pending in the event queue of the target thread.
275 Using the optional [opt -head] switch, scripts posted to the thread's
276 event queue can be placed on the head, instead on the tail of the queue,
277 thus being executed in the LIFO fashion.
278
279
280 [call [cmd thread::broadcast] [arg script]]
281
282 This command passes a [arg script] to all threads created by the
283 package for execution. It does not wait for response from any of
284 the threads.
285
286 [call [cmd thread::wait]]
287
288 This enters the event loop so a thread can receive messages from
289 the [cmd thread::send] command. This command should only be used
290 within the script passed to the [cmd thread::create]. It should
291 be the very last command in the script. If this is not the case,
292 the exiting thread will continue executing the script lines past
293 the [cmd thread::wait] which is usually not what you want and/or
294 expect.
295
296 [example {
297     set t1 [thread::create {
298         #
299         # Do some initialization work here
300         #
301         thread::wait ; # Enter the event loop
302     }]
303 }]
304
305 [call [cmd thread::eval] [opt {-lock mutex}] [arg arg] [opt {arg ...}]]
306
307 This command concatenates passed arguments and evaluates the
308 resulting script under the mutex protection. If no mutex is
309 specified by using the [opt {-lock mutex}] optional argument,
310 the internal static mutex is used.
311
312
313 [call [cmd thread::join] [arg id]]
314
315 This command waits for the thread with ID [arg id] to exit and
316 then returns it's exit code. Errors will be returned for threads
317 which are not joinable or already waited upon by another thread.
318 Upon the join the handle of the thread has gone out of scope and
319 should not be used any more.
320
321
322 [call [cmd thread::configure] [arg id] [opt option] [opt value] [opt ...]]
323
324 This command configures various low-level aspects of the thread with
325 ID [arg id] in the similar way as the standard Tcl command
326 [cmd fconfigure] configures some Tcl channel options. Options currently
327 supported are: [option -eventmark] and [option -unwindonerror].
328
329 [para]
330
331 The [option -eventmark] option, when set, limits the number of
332 asynchronously posted scripts to the thread event loop.
333 The [cmd {thread::send -async}] command will block until the number
334 of pending scripts in the event loop does not drop below the value
335 configured with [option -eventmark]. Default value for the
336 [option -eventmark] is 0 (zero) which effectively disables the checking,
337 i.e. allows for unlimited number of posted scripts.
338
339 [para]
340
341 The [option -unwindonerror] option, when set, causes the
342 target thread to unwind if the result of the script processing
343 resulted in error. Default value for the [option -unwindonerror]
344 is 0 (false), i.e. thread continues to process scripts after one
345 of the posted scripts fails.
346
347
348 [call [cmd thread::transfer] [arg id] [arg channel]]
349
350 This moves the specified [arg channel] from the current thread
351 and interpreter to the main interpreter of the thread with the
352 given [arg id]. After the move the current interpreter has no
353 access to the channel any more, but the main interpreter of the
354 target thread will be able to use it from now on.
355 The command waits until the other thread has incorporated the
356 channel. Because of this it is possible to deadlock the
357 participating threads by commanding the other through a
358 synchronous [cmd thread::send] to transfer a channel to us.
359 This easily extends into longer loops of threads waiting for
360 each other. Other restrictions: the channel in question must
361 not be shared among multiple interpreters running in the
362 sending thread. This automatically excludes the special channels
363 for standard input, output and error.
364
365 [para]
366
367 Due to the internal Tcl core implementation and the restriction on
368 transferring shared channels, one has to take extra measures when
369 transferring socket channels created by accepting the connection
370 out of the [cmd socket] commands callback procedures:
371
372 [example {
373     socket -server _Accept 2200
374     proc _Accept {s ipaddr port} {
375         after idle [list Accept $s $ipaddr $port]
376     }
377     proc Accept {s ipaddr port} {
378         set tid [thread::create]
379         thread::transfer $tid $s
380     }
381 }]
382
383 [call [cmd thread::detach] [arg channel]]
384
385 This detaches the specified [arg channel] from the current thread and
386 interpreter. After that, the current interpreter has no access to the
387 channel any more. The channel is in the parked state until some other
388 (or the same) thread attaches the channel again with [cmd thread::attach].
389 Restrictions: same as for transferring shared channels with the
390 [cmd thread::transfer] command.
391
392 [call [cmd thread::attach] [arg channel]]
393
394 This attaches the previously detached [arg channel] in the
395 current thread/interpreter. For already existing channels,
396 the command does nothing, i.e. it is not an error to attach the
397 same channel more than once. The first operation will actually
398 perform the operation, while all subsequent operation will just
399 do nothing. Command throws error if the [arg channel] cannot be
400 found in the list of detached channels and/or in the current
401 interpreter.
402
403 [call [cmd thread::mutex]]
404
405 Mutexes are most common thread synchronization primitives.
406 They are used to synchronize access from two or more threads to one or
407 more shared resources. This command provides script-level access to
408 exclusive and/or recursive mutexes. Exclusive mutexes can be locked
409 only once by one thread, while recursive mutexes can be locked many
410 times by the same thread. For recursive mutexes, number of lock and
411 unlock operations must match, otherwise, the mutex will never be
412 released, which would lead to various deadlock situations.
413 [para]
414 Care has to be taken when using mutexes in an multithreading program.
415 Improper use of mutexes may lead to various deadlock situations,
416 especially when using exclusive mutexes.
417
418 [para]
419
420 The [cmd thread::mutex] command supports following subcommands and options:
421
422 [list_begin definitions]
423
424 [call [cmd thread::mutex] [method create] [opt -recursive]]
425
426 Creates the mutex and returns it's opaque handle. This handle
427 should be used for any future reference to the newly created mutex.
428 If no optional [opt -recursive] argument was specified, the command
429 creates the exclusive mutex. With the [opt -recursive] argument,
430 the command creates a recursive mutex.
431
432 [call [cmd thread::mutex] [method destroy] [arg mutex]]
433
434 Destroys the [arg mutex]. Mutex should be in unlocked state before
435 the destroy attempt. If the mutex is locked, the command will throw
436 Tcl error.
437
438 [call [cmd thread::mutex] [method lock] [arg mutex]]
439
440 Locks the [arg mutex]. Locking the exclusive mutex may throw Tcl
441 error if on attempt to lock the same mutex twice from the same
442 thread. If your program logic forces you to lock the same mutex
443 twice or more from the same thread (this may happen in recursive
444 procedure invocations) you should consider using the recursive mutexes.
445
446 [call [cmd thread::mutex] [method unlock] [arg mutex]]
447
448 Unlocks the [arg mutex] so some other thread may lock it again.
449 Attempt to unlock the already unlocked mutex will throw Tcl error.
450
451 [list_end]
452
453 [para]
454
455 [call [cmd thread::rwmutex]]
456
457 This command creates many-readers/single-writer mutexes. Reader/writer
458 mutexes allow you to serialize access to a shared resource more optimally.
459 In situations where a shared resource gets mostly read and seldom modified,
460 you might gain some performance by using reader/writer mutexes instead of
461 exclusive or recursive mutexes.
462 [para]
463 For reading the resource, thread should obtain a read lock on the resource.
464 Read lock is non-exclusive, meaning that more than one thread can
465 obtain a read lock to the same resource, without waiting on other readers.
466 For changing the resource, however, a thread must obtain a exclusive
467 write lock. This lock effectively blocks all threads from gaining the
468 read-lock while the resource is been modified by the writer thread.
469 Only after the write lock has been released, the resource may be read-locked
470 again.
471
472 [para]
473
474 The [cmd thread::rwmutex] command supports following subcommands and options:
475
476 [list_begin definitions]
477
478 [call [cmd thread::rwmutex] [method create]]
479
480 Creates the reader/writer mutex and returns it's opaque handle.
481 This handle should be used for any future reference to the newly
482 created mutex.
483
484 [call [cmd thread::rwmutex] [method destroy] [arg mutex]]
485
486 Destroys the reader/writer [arg mutex]. If the mutex is already locked,
487 attempt to destroy it will throw Tcl error.
488
489 [call [cmd thread::rwmutex] [method rlock] [arg mutex]]
490
491 Locks the [arg mutex] for reading. More than one thread may read-lock
492 the same [arg mutex] at the same time.
493
494 [call [cmd thread::rwmutex] [method wlock] [arg mutex]]
495
496 Locks the [arg mutex] for writing. Only one thread may write-lock
497 the same [arg mutex] at the same time. Attempt to write-lock same
498 [arg mutex] twice from the same thread will throw Tcl error.
499
500 [call [cmd thread::rwmutex] [method unlock] [arg mutex]]
501
502 Unlocks the [arg mutex] so some other thread may lock it again.
503 Attempt to unlock already unlocked [arg mutex] will throw Tcl error.
504
505 [list_end]
506
507 [para]
508
509 [call [cmd thread::cond]]
510
511 This command provides script-level access to condition variables.
512 A condition variable creates a safe environment for the program
513 to test some condition, sleep on it when false and be awakened
514 when it might have become true. A condition variable is always
515 used in the conjunction with an exclusive mutex. If you attempt
516 to use other type of mutex in conjunction with the condition
517 variable, a Tcl error will be thrown.
518
519 [para]
520
521 The command supports following subcommands and options:
522
523 [list_begin definitions]
524
525 [call [cmd thread::cond] [method create]]
526
527 Creates the condition variable and returns it's opaque handle.
528 This handle should be used for any future reference to newly
529 created condition variable.
530
531 [call [cmd thread::cond] [method destroy] [arg cond]]
532
533 Destroys condition variable [arg cond]. Extreme care has to be taken
534 that nobody is using (i.e. waiting on) the condition variable,
535 otherwise unexpected errors may happen.
536
537 [call [cmd thread::cond] [method notify] [arg cond]]
538
539 Wakes up all threads waiting on the condition variable [arg cond].
540
541 [call [cmd thread::cond] [method wait] [arg cond] [arg mutex] [opt ms]]
542
543 This command is used to suspend program execution until the condition
544 variable [arg cond] has been signalled or the optional timer has expired.
545 The exclusive [arg mutex] must be locked by the calling thread on entrance
546 to this command. If the mutex is not locked, Tcl error is thrown.
547 While waiting on the [arg cond], the command releases [arg mutex].
548 Before returning to the calling thread, the command re-acquires the
549 [arg mutex] again. Unlocking the [arg mutex] and waiting on the
550 condition variable [arg cond] is done atomically.
551
552 [para]
553
554 The [option ms] command option, if given, must be an integer specifying
555 time interval in milliseconds the command waits to be signalled.
556 Otherwise the command waits on condition notify forever.
557
558 [para]
559
560 In multithreading programs, there are many situations where a thread has
561 to wait for some event to happen until it is allowed to proceed.
562 This is usually accomplished by repeatedly testing a condition under the
563 mutex protection and waiting on the condition variable until the condition
564 evaluates to true:
565
566 [example {
567     set mutex [thread::mutex create]
568     set cond  [thread::cond  create]
569
570     thread::mutex lock $mutex
571     while {<some_condition_is_true>} {
572         thread::cond wait $cond $mutex
573     }
574     # Do some work under mutex protection
575     thread::mutex unlock $mutex
576 }]
577
578 Repeated testing of the condition is needed since the condition variable
579 may get signalled without the condition being actually changed (spurious
580 thread wake-ups, for example).
581
582 [list_end]
583
584 [list_end]
585
586 [section DISCUSSION]
587 The fundamental threading model in Tcl is that there can be one or
588 more Tcl interpreters per thread, but each Tcl interpreter should
589 only be used by a single thread which created it.
590 A "shared memory" abstraction is awkward to provide in Tcl because
591 Tcl makes assumptions about variable and data ownership. Therefore
592 this extension supports a simple form of threading where the main
593 thread can manage several background, or "worker" threads.
594 For example, an event-driven server can pass requests to worker
595 threads, and then await responses from worker threads or new client
596 requests. Everything goes through the common Tcl event loop, so
597 message passing between threads works naturally with event-driven I/O,
598 [cmd vwait] on variables, and so forth. For the transfer of bulk
599 information it is possible to move channels between the threads.
600
601 [para]
602
603 For advanced multithreading scripts, script-level access to two
604 basic synchronization primitives, mutex and condition variables,
605 is also supported.
606
607 [see_also tsv tpool ttrace [uri http://www.tcl.tk/doc/howto/thread_model.html]]
608
609 [keywords thread events {message passing} synchronization mutex]
610
611 [manpage_end]