Some questions about https://play.golang.org/p/FCydAiNZNWv

https://play.golang.org/p/FCydAiNZNWv

I don’t understand this: time.Sleep(time.Second * 2)
I don’t understand this: runtime.Gosched() // tells runtime to yield processor to other goroutine
What is “counter”?

2 Likes

Hi, Cherolyn, based on how that part is commented out and then followed up with runtime.Gosched(), I’m under the impression that whoever wrote this was trying to force a goroutine to go to sleep so that another goroutine can run. counter is a global variable that the goroutines created in that for loop is incrementing.

Without some more context, I’m not sure what this piece of code is supposed to do and/or demonstrate, though.

2 Likes

The time.Sleep(time.Second * 2) is to make the goroutine pause for 2 seconds. It has been commented out though. It has the side effect to let other goroutine run.

The runtime.Gosched() tells the runtime to suspend the goroutine and let other goroutine run. It is a special kind of pause in that other goroutines will run. It takes much less time than 2 seconds to complete.

The counter is a global variable that is incremented.

I guess this code is to demonstrate the effect of concurrent increment of a counter. In this code, there is a mutex that guards the increment operation. Because of the mutex, only one goroutine can execute the code between the Lock and Unlock. The net result is that the final counter value will be the value of gs.

Without the mutex Lock and Unlock, the counter would have a different value (less than gs).

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.