Goroutines and mutex

88 views
Skip to first unread message

Денис Мухортов

unread,
Nov 28, 2021, 10:19:07 AM11/28/21
to golang-nuts
Why are the values not incremented when declaring a structure with mutex in goroutines?
https://go.dev/play/p/bPc1bg0AvJ4

And what is the actual point in declaring something in anonymous functions, if in my experience it always works without it?

Axel Wagner

unread,
Nov 28, 2021, 11:01:22 AM11/28/21
to Денис Мухортов, golang-nuts
On Sun, Nov 28, 2021 at 4:19 PM Денис Мухортов <muhorto...@gmail.com> wrote:
Why are the values not incremented when declaring a structure with mutex in goroutines?
https://go.dev/play/p/bPc1bg0AvJ4

You have multiple problems:
1. You are passing `counter` to the goroutine as a value, making a copy
2. You have to call `wg.Add` *before* the `go` statement, otherwise it is possible that the loop finishes before any of the goroutines get scheduled, causing `wg.Wait` to immediately return
3. The playground likely doesn't actually let you consume 10s of CPU time. Normally, the emulated time of the playground means that sleeping for 10s is not a problem (as it doesn't *actually* sleep), but you are busy-looping, so you are actually taking up CPU time.

Here is a fixed version: https://go.dev/play/p/EZwW7clnORm
It still times out in the playground, though.
 
And what is the actual point in declaring something in anonymous functions, if in my experience it always works without it?

I don't understand this question.
 

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/7f3aaf03-0705-4e19-b027-68764b185b4dn%40googlegroups.com.

Levieux Michel

unread,
Nov 28, 2021, 11:09:19 AM11/28/21
to Денис Мухортов, golang-nuts
The problem here is you are sending a copy of counter to the anonymous function. You need to either not pass it and use the outer-scope counter directly in the function, or pass a reference to the counter to the function.

Hope this helps.

--
Reply all
Reply to author
Forward
0 new messages