Events: Difference between revisions

2,055 bytes added ,  13 years ago
→‎{{header|Go}}: added variant solutions using the standard library.
(Go solution)
(→‎{{header|Go}}: added variant solutions using the standard library.)
Line 159:
}</lang>
=={{header|Go}}==
===Channel===
A Go channel can represent an manual-reset event, as described by the task. The two states of signaled and reset correspond to the presence or absence of a value on the channel. The program signals by sending a value on the channel. The event is reset when the waiting task explicitly executes the channel receive operation, <-event.
<lang go>package main
 
Line 189 ⟶ 190:
Sat Feb 19 00:11:51 EST 2011 event reset by task
</pre>
===Semacquire===
The functions semacquire and semrelease, in the runtime package of the standard library, provide a manual reset event capability exactly as described by the task.
 
Now, documentation states, "It is intended as a simple sleep primitive for use by the synchronization library and should not be used directly." Yet it is a well defined primitive and seems unlikely to be taken away in future releases. The warning can be considered discouragement from mucking with obscure low-level primitives when real-world problems can almost always be better expressed with higher-level language and library features. This RC task, however, not being a real-world problem, is solved most fundamentally with this pair of functions.
 
The event, as a object with two states, is now simply a uint32. The two states are 0 and 1 representing reset and signaled, respectively. Semrelease represents event notification, and increments s. Semacquire represents the explicit reset, decrementing s.
<lang go>package main
 
import (
"fmt"
"runtime"
"time"
)
 
func main() {
fmt.Println(time.LocalTime(), "program start")
var s uint32
go func() {
fmt.Println(time.LocalTime(), "task start")
runtime.Semacquire(&s)
fmt.Println(time.LocalTime(), "event reset by task")
}()
fmt.Println(time.LocalTime(), "program sleeping")
time.Sleep(1e9)
fmt.Println(time.LocalTime(), "program signaling event")
runtime.Semrelease(&s)
time.Sleep(1e8)
}</lang>
===Variants===
The task description mentions a pulse event. Go has direct support for this in the Broadcast method of the Cond type in the sync package.
 
Also, in the time package, the Timer type offers different ways of starting a task after a specified delay, achieving the end result of this RC task, if not exposing all of the low-level synchronization details involved.
 
=={{header|Haskell}}==
1,707

edits