The code in the task uses multiple goroutines to increment the value of the variable counter. The number of goroutines is determined by the workers variable. It is logical to assume that the value of the variable counter should be equal to the number of workers. However, due to data races, this does not happen, and the final value of the variable counter is almost always less than the number of workers. This is especially noticeable with a large number of workers (> 500). Using the semaphore principle, synchronize the work of the goroutines so that each one has access to the variable in its own time interval.
Synchronization with channels
No data running
Report a typo
Write a program in Go
package main
import (
"fmt"
"time"
)
func main() {
// DO NOT delete or modify the lines below, they are used in the code
var workers, counter int64
generator(&workers, &counter)
sync := ?
for range make([]struct{}, workers) {
go func() {
?
counter++ // DO NOT delete or modify this line of code
?
}()
}
// DO NOT delete or modify the lines below, they are used for checking the answer
time.Sleep(5 * time.Second)
fmt.Println("done")
check(workers, counter)
}
___
By continuing, you agree to the JetBrains Academy Terms of Service as well as Hyperskill Terms of Service and Privacy Policy.
Create a free account to access the full topic
By continuing, you agree to the JetBrains Academy Terms of Service as well as Hyperskill Terms of Service and Privacy Policy.