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() {
// librarybuffered analogychannel perused WPas articlea counting semaphore
librarianrooms := make(chan int, nRooms)
for i := 0; i < nRooms; i++ {
rooms <- 1
}
// WaitGroup used to wait untilfor all students to have studied before terminating program
// before terminating program
var studied sync.WaitGroup
studied.Add(nStudents)
// nStudents run concurrently
for i := 0; i < nStudents; i++ {
go student(librarianrooms, &studied)
}
// wait until all students have studied before terminating program
studied.Wait()
}
 
func student(studyRoomrooms chan int, studied *sync.WaitGroup) {
studyRoom <-rooms 1 // acquire operation
// report per task descrption. also exercise count operation
fmt.Printf("Room entered. Count is %d. Studying...\n",
nRooms-len(studyRoomrooms)) // len function provides count operation
time.Sleep(2 * time.Second) // sleep per task description
rooms <-studyRoom 1 // release operation
studied.Done() // signal that student // signalis done
}</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.
1,707

edits