'\"
'\" Copyright (c) 1995-1996 Sun Microsystems, Inc.
'\"
'\" See the file "license.terms" for information on usage and redistribution
'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
'\"
.TH vwait n 8.0 Tcl "Tcl Built-In Commands"
.\" The -*- nroff -*- definitions below are for supplemental macros used
.\" in Tcl/Tk manual entries.
.\"
.\" .AP type name in/out ?indent?
.\"	Start paragraph describing an argument to a library procedure.
.\"	type is type of argument (int, etc.), in/out is either "in", "out",
.\"	or "in/out" to describe whether procedure reads or modifies arg,
.\"	and indent is equivalent to second arg of .IP (shouldn't ever be
.\"	needed;  use .AS below instead)
.\"
.\" .AS ?type? ?name?
.\"	Give maximum sizes of arguments for setting tab stops.  Type and
.\"	name are examples of largest possible arguments that will be passed
.\"	to .AP later.  If args are omitted, default tab stops are used.
.\"
.\" .BS
.\"	Start box enclosure.  From here until next .BE, everything will be
.\"	enclosed in one large box.
.\"
.\" .BE
.\"	End of box enclosure.
.\"
.\" .CS
.\"	Begin code excerpt.
.\"
.\" .CE
.\"	End code excerpt.
.\"
.\" .VS ?version? ?br?
.\"	Begin vertical sidebar, for use in marking newly-changed parts
.\"	of man pages.  The first argument is ignored and used for recording
.\"	the version when the .VS was added, so that the sidebars can be
.\"	found and removed when they reach a certain age.  If another argument
.\"	is present, then a line break is forced before starting the sidebar.
.\"
.\" .VE
.\"	End of vertical sidebar.
.\"
.\" .DS
.\"	Begin an indented unfilled display.
.\"
.\" .DE
.\"	End of indented unfilled display.
.\"
.\" .SO ?manpage?
.\"	Start of list of standard options for a Tk widget. The manpage
.\"	argument defines where to look up the standard options; if
.\"	omitted, defaults to "options". The options follow on successive
.\"	lines, in three columns separated by tabs.
.\"
.\" .SE
.\"	End of list of standard options for a Tk widget.
.\"
.\" .OP cmdName dbName dbClass
.\"	Start of description of a specific option.  cmdName gives the
.\"	option's name as specified in the class command, dbName gives
.\"	the option's name in the option database, and dbClass gives
.\"	the option's class in the option database.
.\"
.\" .UL arg1 arg2
.\"	Print arg1 underlined, then print arg2 normally.
.\"
.\" .QW arg1 ?arg2?
.\"	Print arg1 in quotes, then arg2 normally (for trailing punctuation).
.\"
.\" .PQ arg1 ?arg2?
.\"	Print an open parenthesis, arg1 in quotes, then arg2 normally
.\"	(for trailing punctuation) and then a closing parenthesis.
.\"
.\"	# Set up traps and other miscellaneous stuff for Tcl/Tk man pages.
.if t .wh -1.3i ^B
.nr ^l \n(.l
.ad b
.\"	# Start an argument description
.de AP
.ie !"\\$4"" .TP \\$4
.el \{\
.   ie !"\\$2"" .TP \\n()Cu
.   el          .TP 15
.\}
.ta \\n()Au \\n()Bu
.ie !"\\$3"" \{\
\&\\$1 \\fI\\$2\\fP (\\$3)
.\".b
.\}
.el \{\
.br
.ie !"\\$2"" \{\
\&\\$1	\\fI\\$2\\fP
.\}
.el \{\
\&\\fI\\$1\\fP
.\}
.\}
..
.\"	# define tabbing values for .AP
.de AS
.nr )A 10n
.if !"\\$1"" .nr )A \\w'\\$1'u+3n
.nr )B \\n()Au+15n
.\"
.if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n
.nr )C \\n()Bu+\\w'(in/out)'u+2n
..
.AS Tcl_Interp Tcl_CreateInterp in/out
.\"	# BS - start boxed text
.\"	# ^y = starting y location
.\"	# ^b = 1
.de BS
.br
.mk ^y
.nr ^b 1u
.if n .nf
.if n .ti 0
.if n \l'\\n(.lu\(ul'
.if n .fi
..
.\"	# BE - end boxed text (draw box now)
.de BE
.nf
.ti 0
.mk ^t
.ie n \l'\\n(^lu\(ul'
.el \{\
.\"	Draw four-sided box normally, but don't draw top of
.\"	box if the box started on an earlier page.
.ie !\\n(^b-1 \{\
\h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
.\}
.el \}\
\h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
.\}
.\}
.fi
.br
.nr ^b 0
..
.\"	# VS - start vertical sidebar
.\"	# ^Y = starting y location
.\"	# ^v = 1 (for troff;  for nroff this doesn't matter)
.de VS
.if !"\\$2"" .br
.mk ^Y
.ie n 'mc \s12\(br\s0
.el .nr ^v 1u
..
.\"	# VE - end of vertical sidebar
.de VE
.ie n 'mc
.el \{\
.ev 2
.nf
.ti 0
.mk ^t
\h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n'
.sp -1
.fi
.ev
.\}
.nr ^v 0
..
.\"	# Special macro to handle page bottom:  finish off current
.\"	# box/sidebar if in box/sidebar mode, then invoked standard
.\"	# page bottom macro.
.de ^B
.ev 2
'ti 0
'nf
.mk ^t
.if \\n(^b \{\
.\"	Draw three-sided box if this is the box's first page,
.\"	draw two sides but no top otherwise.
.ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
.el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
.\}
.if \\n(^v \{\
.nr ^x \\n(^tu+1v-\\n(^Yu
\kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c
.\}
.bp
'fi
.ev
.if \\n(^b \{\
.mk ^y
.nr ^b 2
.\}
.if \\n(^v \{\
.mk ^Y
.\}
..
.\"	# DS - begin display
.de DS
.RS
.nf
.sp
..
.\"	# DE - end display
.de DE
.fi
.RE
.sp
..
.\"	# SO - start of list of standard options
.de SO
'ie '\\$1'' .ds So \\fBoptions\\fR
'el .ds So \\fB\\$1\\fR
.SH "STANDARD OPTIONS"
.LP
.nf
.ta 5.5c 11c
.ft B
..
.\"	# SE - end of list of standard options
.de SE
.fi
.ft R
.LP
See the \\*(So manual entry for details on the standard options.
..
.\"	# OP - start of full description for a single option
.de OP
.LP
.nf
.ta 4c
Command-Line Name:	\\fB\\$1\\fR
Database Name:	\\fB\\$2\\fR
Database Class:	\\fB\\$3\\fR
.fi
.IP
..
.\"	# CS - begin code excerpt
.de CS
.RS
.nf
.ta .25i .5i .75i 1i
..
.\"	# CE - end code excerpt
.de CE
.fi
.RE
..
.\"	# UL - underline word
.de UL
\\$1\l'|0\(ul'\\$2
..
.\"	# QW - apply quotation marks to word
.de QW
.ie '\\*(lq'"' ``\\$1''\\$2
.\"" fix emacs highlighting
.el \\*(lq\\$1\\*(rq\\$2
..
.\"	# PQ - apply parens and quotation marks to word
.de PQ
.ie '\\*(lq'"' (``\\$1''\\$2)\\$3
.\"" fix emacs highlighting
.el (\\*(lq\\$1\\*(rq\\$2)\\$3
..
.\"	# QR - quoted range
.de QR
.ie '\\*(lq'"' ``\\$1''\\-``\\$2''\\$3
.\"" fix emacs highlighting
.el \\*(lq\\$1\\*(rq\\-\\*(lq\\$2\\*(rq\\$3
..
.\"	# MT - "empty" string
.de MT
.QW ""
..
.BS
'\" Note:  do not modify the .SH NAME line immediately below!
.SH NAME
vwait \- Process events until a variable is written
.SH SYNOPSIS
\fBvwait\fI varName\fR
.sp
\fBvwait\fR ?\fIoptions\fR? ?\fIvarName ...\fR?
.BE
.SH DESCRIPTION
.PP
This command enters the Tcl event loop to process events, blocking
the application if no events are ready.  It continues processing
events until some event handler sets the value of the global variable
\fIvarName\fR.  Once \fIvarName\fR has been set, the \fBvwait\fR
command will return as soon as the event handler that modified
\fIvarName\fR completes.  The \fIvarName\fR argument is always interpreted as
a variable name with respect to the global namespace, but can refer to any
namespace's variables if the fully-qualified name is given.
.PP
In the second more complex command form \fIoptions\fR allow for finer
control of the wait operation and to deal with multiple event sources.
\fIOptions\fR can be made up of:
.\" OPTION: --
.TP
\fB\-\-\fR
.
Marks the end of options. All following arguments are handled as
variable names.
.\" OPTION: -all
.TP
\fB\-all\fR
.
All conditions for the wait operation must be met to complete the
wait operation. Otherwise (the default) the first event completes
the wait.
.\" OPTION: -extended
.TP
\fB\-extended\fR
.
An extended result in list form is returned, see below for explanation.
.\" OPTION: -nofileevents
.TP
\fB\-nofileevents\fR
.
File events are not handled in the wait operation.
.\" OPTION: -noidleevents
.TP
\fB\-noidleevents\fR
.
Idle handlers are not invoked during the wait operation.
.\" OPTION: -notimerevents
.TP
\fB\-notimerevents\fR
.
Timer handlers are not serviced during the wait operation.
.\" OPTION: -nowindowevents
.TP
\fB\-nowindowevents\fR
.
Events of the windowing system are not handled during the wait operation.
.\" OPTION: -readable
.TP
\fB\-readable\fI channel\fR
.
\fIChannel\fR must name a Tcl channel open for reading. If \fIchannel\fR
is or becomes readable the wait operation completes.
.\" OPTION: -timeout
.TP
\fB\-timeout\fI milliseconds\fR
.
The wait operation is constrained to \fImilliseconds\fR.
.\" OPTION: -variable
.TP
\fB\-variable\fI varName\fR
.
\fIVarName\fR must be the name of a global variable. Writing or
unsetting this variable completes the wait operation.
.\" OPTION: -writable
.TP
\fB\-writable\fI channel\fR
.
\fIChannel\fR must name a Tcl channel open for writing. If \fIchannel\fR
is or becomes writable the wait operation completes.
.PP
The result returned by \fBvwait\fR is for the simple form an empty
string. If the \fB\-timeout\fR option is specified, the result is the
number of milliseconds remaining when the wait condition has been
met, or -1 if the wait operation timed out.
.PP
If the \fB\-extended\fR option is specified, the result is made up
of a Tcl list with an even number of elements. Odd elements
take the values \fBreadable\fR, \fBtimeleft\fR, \fBvariable\fR,
and \fBwritable\fR. Even elements are the corresponding variable
and channel names or the remaining number of milliseconds.
The list is ordered by the occurrences of the event(s) with the
exception of \fBtimeleft\fR which always comes last.
.PP
In some cases the \fBvwait\fR command may not return immediately
after \fIvarName\fR et.al. is set. This happens if the event handler
that sets \fIvarName\fR does not complete immediately.  For example,
if an event handler sets \fIvarName\fR and then itself calls
\fBvwait\fR to wait for a different variable, then it may not return
for a long time.  During this time the top-level \fBvwait\fR is
blocked waiting for the event handler to complete, so it cannot
return either. (See the \fBNESTED VWAITS BY EXAMPLE\fR below.)
.PP
To be clear, \fImultiple \fBvwait\fI calls will nest and will not happen in
parallel\fR.  The outermost call to \fBvwait\fR will not return until all the
inner ones do.  It is recommended that code should never nest \fBvwait\fR
calls (by avoiding putting them in event callbacks) but when that is not
possible, care should be taken to add interlock variables to the code to
prevent all reentrant calls to \fBvwait\fR that are not \fIstrictly\fR
necessary. Be aware that the synchronous modes of operation of some Tcl
packages (e.g.,\ \fBhttp\fR) use \fBvwait\fR internally; if using the event
loop, it is best to use the asynchronous callback-based modes of operation of
those packages where available.
.SH EXAMPLES
.PP
Run the event-loop continually until some event calls \fBexit\fR.
(You can use any variable not mentioned elsewhere, but the name
\fIforever\fR reminds you at a glance of the intent.)
.PP
.CS
\fBvwait\fR forever
.CE
.PP
Wait five seconds for a connection to a server socket, otherwise
close the socket and continue running the script:
.PP
.CS
# Initialise the state
after 5000 set state timeout
set server [socket -server accept 12345]
proc accept {args} {
    global state connectionInfo
    set state accepted
    set connectionInfo $args
}

# Wait for something to happen
\fBvwait\fR state

# Clean up events that could have happened
close $server
after cancel set state timeout

# Do something based on how the vwait finished...
switch $state {
    timeout {
        puts "no connection on port 12345"
    }
    accepted {
       puts "connection: $connectionInfo"
       puts [lindex $connectionInfo 0] "Hello there!"
    }
}
.CE
.PP
A command that will wait for some time delay by waiting for a namespace
variable to be set.  Includes an interlock to prevent nested waits.
.PP
.CS
namespace eval example {
    variable v done
    proc wait {delay} {
        variable v
        if {$v ne "waiting"} {
            set v waiting
            after $delay [namespace code {set v done}]
            \fBvwait\fR [namespace which -variable v]
        }
        return $v
    }
}
.CE
.PP
When running inside a \fBcoroutine\fR, an alternative to using \fBvwait\fR is
to \fByield\fR to an outer event loop and to get recommenced when the variable
is set, or at an idle moment after that.
.PP
.CS
coroutine task apply {{} {
    # simulate [after 1000]
    after 1000 [info coroutine]
    yield

    # schedule the setting of a global variable, as normal
    after 2000 {set var 1}

    # simulate [\fBvwait\fR var]
    proc updatedVar {task args} {
        after idle $task
        trace remove variable ::var write "updatedVar $task"
    }
    trace add variable ::var write "updatedVar [info coroutine]"
    yield
}}
.CE
.SS "NESTED VWAITS BY EXAMPLE"
.PP
This example demonstrates what can happen when the \fBvwait\fR command is
nested. The script will never finish because the waiting for the \fIa\fR
variable never finishes; that \fBvwait\fR command is still waiting for a
script scheduled with \fBafter\fR to complete, which just happens to be
running an inner \fBvwait\fR (for \fIb\fR) even though the event that the
outer \fBvwait\fR was waiting for (the setting of \fIa\fR) has occurred.
.PP
.CS
after 500 {
    puts "waiting for b"
    \fBvwait\fR b
    puts "b was set"
}
after 1000 {
    puts "setting a"
    set a 10
}
puts "waiting for a"
\fBvwait\fR a
puts "a was set"
puts "setting b"
set b 42
.CE
.PP
If you run the above code, you get this output:
.PP
.CS
waiting for a
waiting for b
setting a
.CE
.PP
The script will never print
.QW "a was set"
until after it has printed
.QW "b was set"
because of the nesting of \fBvwait\fR commands, and yet \fIb\fR will not be
set until after the outer \fBvwait\fR returns, so the script has deadlocked.
The only ways to avoid this are to either structure the overall program in
continuation-passing style or to use \fBcoroutine\fR to make the continuations
implicit. The first of these options would be written as:
.PP
.CS
after 500 {
    puts "waiting for b"
    trace add variable b write {apply {args {
        global a b
        trace remove variable ::b write \e
                [lrange [info level 0] 0 1]
        puts "b was set"
        set ::done ok
    }}}
}
after 1000 {
    puts "setting a"
    set a 10
}
puts "waiting for a"
trace add variable a write {apply {args {
    global a b
    trace remove variable a write [lrange [info level 0] 0 1]
    puts "a was set"
    puts "setting b"
    set b 42
}}}
\fBvwait\fR done
.CE
.PP
The second option, with \fBcoroutine\fR and some helper procedures, is done
like this:
.PP
.CS
# A coroutine-based wait-for-variable command
proc waitvar globalVar {
    trace add variable ::$globalVar write \e
            [list apply {{v c args} {
        trace remove variable $v write \e
                [lrange [info level 0] 0 3]
        after 0 $c
    }} ::$globalVar [info coroutine]]
    yield
}
# A coroutine-based wait-for-some-time command
proc waittime ms {
    after $ms [info coroutine]
    yield
}

coroutine task-1 eval {
    puts "waiting for a"
    waitvar a
    puts "a was set"
    puts "setting b"
    set b 42
}
coroutine task-2 eval {
    waittime 500
    puts "waiting for b"
    waitvar b
    puts "b was set"
    set done ok
}
coroutine task-3 eval {
    waittime 1000
    puts "setting a"
    set a 10
}
\fBvwait\fR done
.CE
.SH "SEE ALSO"
global(n), update(n)
.SH KEYWORDS
asynchronous I/O, event, variable, wait
'\" Local Variables:
'\" mode: nroff
'\" fill-column: 78
'\" End:
