Events: Difference between revisions

1,910 bytes added ,  14 years ago
Added Oz.
(Added Oz.)
Line 163:
Note: Because there is no serialization of the text output, there is a chance that it will appear interleaved.
 
=={{header|Oz}}==
{{trans|Haskell}}
 
Events can be implemented as mutable references to dataflow variables:
 
<lang oz>declare
fun {NewEvent}
{NewCell _}
end
 
proc {SignalEvent Event}
@Event = unit
end
 
proc {ResetEvent Event}
Event := _
end
 
proc {WaitEvent Event}
{Wait @Event}
end
 
E = {NewEvent}
in
thread
{System.showInfo "[2] Waiting for event..."}
{WaitEvent E}
{System.showInfo "[2] Received event."}
end
 
{System.showInfo "[1] Waiting 1 second..."}
{Delay 1000}
{System.showInfo "[1] Signaling event."}
{SignalEvent E}</lang>
 
However, this code is quite unidiomatic. If we need to wait for an event just once (like in this example), we can simply use a dataflow variable, i.e. an event that cannot be reset:
<lang oz>declare
E
in
thread
{System.showInfo "[2] Waiting for event..."}
{Wait E}
{System.showInfo "[2] Received event."}
end
 
{System.showInfo "[1] Waiting 1 second..."}
{Delay 1000}
{System.showInfo "[1] Signaling event."}
E = unit</lang>
 
If we want to synchronize two threads repeatedly and exchange data, it is natural to use ports and streams. Streams are just lists with an unbound tail. A port is basically a pointer to the tail of a list, i.e. it keeps track of where the next event can be written to:
<lang oz>declare
MyPort
in
thread
MyStream
in
{NewPort ?MyStream ?MyPort}
{System.showInfo "[2] Waiting for event..."}
for Event in MyStream do
{System.showInfo "[2] Received event."}
{System.showInfo "[2] Waiting for event again..."}
end
end
 
for do
{System.showInfo "[1] Waiting 1 second..."}
{Delay 1000}
{System.showInfo "[1] Signaling event."}
{Port.send MyPort unit}
end</lang>
It is important to limit the scope of a stream as much as possible to ensure that the already read part of the stream is garbage-collected.
=={{header|Tcl}}==
Tcl has been event-driven since 7.5, but only supported channel and timer events (plus variable traces, which can be used to create event-like entitites). With the addition of coroutines, it becomes much simpler to create general events:
Anonymous user