Metered concurrency: Difference between revisions
Content added Content deleted
(Go solution) |
(→{{header|Go}}: updated to use new WaitGroup feature) |
||
Line 335: | Line 335: | ||
"fmt" |
"fmt" |
||
"time" |
"time" |
||
"sync" |
|||
) |
) |
||
Line 346: | Line 347: | ||
go librarian(acquire, release, count, 10) |
go librarian(acquire, release, count, 10) |
||
nStudents := 20 |
nStudents := 20 |
||
var studied sync.WaitGroup |
|||
studied |
studied.Add(nStudents) |
||
for i := 0; i < nStudents; i++ { |
|||
go student(acquire, release, studied) |
|||
} |
|||
⚫ | |||
for i := 0; i < nStudents; i++ { |
for i := 0; i < nStudents; i++ { |
||
go student(acquire, release, &studied) |
|||
} |
} |
||
⚫ | |||
studied.Wait() |
|||
} |
} |
||
Line 367: | Line 365: | ||
p = nil |
p = nil |
||
} |
} |
||
case <-r: // release operation |
case <-r: // release/v operation |
||
count++ |
count++ |
||
p = a |
p = a |
||
Line 376: | Line 374: | ||
} |
} |
||
func student(a, r |
func student(a, r chan int, studied *sync.WaitGroup) { |
||
a <- 0 // accquire |
a <- 0 // accquire |
||
fmt.Println("Studying...") // report per task descrption |
fmt.Println("Studying...") // report per task descrption |
||
time.Sleep(2e9) // sleep per task description |
time.Sleep(2e9) // sleep per task description |
||
r <- 0 // release |
r <- 0 // release |
||
studied.Done() // signal done |
|||
}</lang> |
}</lang> |
||
Output 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. |
Output 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. |