Metered concurrency: Difference between revisions
→Buffered channel: bug fix. previous version worked with existing compiler but was technically invalid.
No edit summary |
(→Buffered channel: bug fix. previous version worked with existing compiler but was technically invalid.) |
||
Line 414:
Recommended solution for simplicity. Acquire operation is channel send, release is channel receive, and count is provided with len(channel). Also WaitGroup used as a completion checkpoint.
<lang go>package main
import (
"log"
Line 421:
"time"
)
// log package serializes output
var fmt = log.New(os.Stdout, "", 0)
// library analogy per WP article
const nRooms = 10
const nStudents = 20
func main() {
//
for i := 0; i < nRooms; i++ {
rooms <- 1
}
// before terminating program
var studied sync.WaitGroup
studied.Add(nStudents)
// nStudents run concurrently
for i := 0; i < nStudents; i++ {
go student(
}
▲ // wait until all students have studied before terminating program
studied.Wait()
}
func student(
// report per task descrption. also exercise count operation
fmt.Printf("Room entered. Count is %d. Studying...\n",
time.Sleep(2 * time.Second) // sleep per task description
rooms <-
studied.Done() // signal that student
}</lang>
Output for this and the other Go programs here shows 10 students studying immediately, about a 2 second pause, 10 more students studying, then another pause of about 2 seconds before returning to the command prompt.
===Sync.Cond===
A more traditional approach implementing a counting semaphore object with sync.Cond. It has a constructor and methods for the three operations requested by the task.
|