Posted to tcl by dbohdan at Thu Apr 09 16:52:02 GMT 2015view raw
- namespace eval ::wordchan {
- namespace export *
- namespace ensemble create
- variable storage {}
- proc initialize {channelId mode} {
- variable storage
- dict set storage $channelId data {}
- dict set storage $channelId ticktock 0
- return [list initialize finalize watch read write]
- }
- proc finalize {channelId} {
- variable storage
- dict unset storage $channelId
- }
- proc watch {channelId eventspec} {}
- proc read {channelId count} {
- # We ignore $count.
- variable storage
- if {[TickTock $channelId] == 0} {
- set chanData [dict get $storage $channelId data]
- dict set storage $channelId data [lrange $chanData 1 end]
- return [lindex $chanData 0]
- } else {
- error EAGAIN
- }
- }
- proc write {channelId data} {
- variable storage
- set chanData [dict get $storage $channelId data]
- dict set storage $channelId data [concat $chanData $data]
- return [string length $data]
- }
- proc TickTock {channelId} {
- variable storage
- set ticktock [dict get $storage $channelId ticktock]
- dict set storage $channelId ticktock [expr {!$ticktock}]
- return $ticktock
- }
- }
- set ch [chan create {read write} ::wordchan]
- chan configure $ch -buffering none
- puts -nonewline $ch [list a]
- puts -nonewline $ch [list b c]
- puts --[read $ch]-- ;# prints "a"
- puts --[read $ch]-- ;# prints "b"