Checkpoint synchronization: Difference between revisions

Go solution
m (→‎{{header|Perl}}: whitespace)
(Go solution)
Line 338:
}
interp.waitAtTop(promiseAllFulfilled(waits))</lang>
=={{header|Go}}==
Currently (January 2011) the most popular checkpoint idiom in Go is,
<lang go>for i := 0; i < nTasks; i++ {
<-done
}</lang>
Code below uses this idiom and completes the task with the workshop scenario, including workers joining and leaving.
<lang go>package main
 
import (
"fmt"
"rand"
"time"
)
 
const nMech = 5
const detailsPerMech = 4
 
func main() {
assemble := make(chan int)
complete := make(chan int, detailsPerMech)
 
go solicit(assemble, complete, nMech*detailsPerMech)
 
for i := 1; i <= nMech; i++ {
for j := 0; j < detailsPerMech; j++ {
assemble <- 0
}
// Go checkpoint idiom
for j := 0; j < detailsPerMech; j++ {
<-complete
}
// checkpoint reached
fmt.Println("mechanism", i, "completed")
}
}
 
func solicit(a, c chan int, nDetails int) {
rand.Seed(time.Nanoseconds())
var id int // worker id, for output
for nDetails > 0 {
time.Sleep(5e8 + rand.Int63n(5e8)) // some random time to find a worker
id++
// contract to assemble a certain number of details
contract := rand.Intn(5) + 1
if contract > nDetails {
contract = nDetails
}
dword := "details"
if contract == 1 {
dword = "detail"
}
fmt.Println("worker", id, "contracted to assemble", contract, dword)
go worker(a, c, contract, id)
nDetails -= contract
}
}
 
func worker(a, c chan int, contract, id int) {
// some random time it takes for this worker to assemble a detail
assemblyTime := 5e8 + rand.Int63n(5e8)
fmt.Println("worker", id, "enters shop")
for i := 0; i < contract; i++ {
<-a
fmt.Println("worker", id, "assembling")
time.Sleep(assemblyTime)
fmt.Println("worker", id, "completed detail")
c <- 0
}
fmt.Println("worker", id, "leaves shop")
}</lang>
Output:
<pre>worker 1 contracted to assemble 2 details
worker 1 enters shop
worker 1 assembling
worker 2 contracted to assemble 5 details
worker 2 enters shop
worker 2 assembling
worker 1 completed detail
worker 1 assembling
worker 2 completed detail
worker 2 assembling
worker 3 contracted to assemble 1 detail
worker 3 enters shop
worker 1 completed detail
worker 1 leaves shop
worker 2 completed detail
mechanism 1 completed
worker 3 assembling
worker 2 assembling
 
...
 
worker 5 completed detail
worker 7 completed detail
worker 7 leaves shop
mechanism 4 completed
worker 6 assembling
worker 5 assembling
worker 6 completed detail
worker 6 assembling
worker 5 completed detail
worker 5 leaves shop
worker 6 completed detail
worker 6 assembling
worker 6 completed detail
worker 6 leaves shop
mechanism 5 completed</pre>
 
=={{header|J}}==
 
1,707

edits