Concurrent computing: Difference between revisions

(→‎{{header|Go}}: updated to use new WaitGroup feature. also simplified a bit.)
Line 325:
 
=={{header|Go}}==
Goroutines started by main() do not continue to run after main exits. To allow them to complete, the program uses a [http://rosettacode.org/wiki/Checkpoint_synchronization checkpoint] mechanism. This is shown implemented two different ways.
When main() exits, that's it. To ensure completion of the goroutines, it is necessary to wait for them.
===Channel===
<lang go>package main
 
import (
"log"
"time"
"os"
"rand"
)
 
func main() {
words := []string{"Enjoy", "Rosetta", "Code"}
l := log.New(os.Stdout, "", 0)
q := make(chan int)
rand.Seed(time.Nanoseconds())
for _, w := range words {
go func(w string) {
time.Sleep(rand.Int63n(1e9))
l.Println(w)
q <- 0
}(w)
}
for i := 0; i < len(words); i++ {
<-q
}
}</lang>
===WaitGroup===
<lang go>package main
 
1,707

edits