Analyze the following Go code for concurrency-related issues. What is its behavior?
Go & Rust interview question for Advanced practice.
Answer
The code is correct and free of data races. It will print 'Counter: 10000'.
Explanation
The correct answer is B. The code is correct. The shared counter variable is accessed by multiple goroutines. However, each access (counter++) is protected by a sync.Mutex, with mutex.Lock() called before the increment and mutex.Unlock() called after. The wg.Wait() ensures that the main goroutine waits for all worker goroutines to finish before printing the final value, so the final read is also safe. The program will correctly print 10000.