Welcome, guest | Sign In | My Account | Store | Cart

Sometimes it is useful to be able to read from a channel but not hang while waiting for data to become available. While this can always be done with file events (and indeed they are used to implement this) it is occassionally easier to just read data and let other events handlers do their business while your "thread" waits for data. Thus bringing us closer to a thread programming model.

Tcl, 26 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
## Returns data from file when there is something that can be read.
## Starts the event loop while waiting.

proc readWithEventLoop {file} {
    global ReadableStatus

    # See that index is unique and does not conflict with other eventReads
    set i 0
    while {[info exists ::ReadableStatus($file,$i)]} {
	incr i
    }
    
    set ReadableStatus($file,$i) 0
    set oldScript [fileevent $file readable]
    
    fileevent $file readable [list set ::ReadableStatus($file,$i) 1]
    
    vwait ::ReadableStatus($file,$i)
    unset ::ReadableStatus($file,$i)
    set r [read $file]

    # Make sure an old event handler is returned.
    fileevent $file readable $oldScript

    return $r
}

Can be especially useful when parsing some simple data. With a pure file event model, one must add extra code to manage the state of parsing. If this procedure is used the parsing engine can just call this when waiting for more data, instead of returning and relying on fileevent commands further up the call stack.

Created by Kristoffer Lawson on Tue, 18 Sep 2001 (MIT)
Tcl recipes (162)
Kristoffer Lawson's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks