-1

I am reading some open source go project and found there are many code implemented as below:

for id, s := range subscribers {
                go func(id string, s *helloSaidSubscriber) {
                    select {
                    case <-s.stop:
                        unsubscribe <- id
                        return
                    default:
                    }

                    select {
                    case <-s.stop:
                        unsubscribe <- id
                    case s.events <- e:
                    case <-time.After(time.Second):
                    }
                }(id, s)
            }

in above code, the inner function go func...(id, s) looks like unnecessary. In other words, what the different if I write code like below:

for id, s := range subscribers {
                
                    select {
                    case <-s.stop:
                        unsubscribe <- id
                        return
                    default:
                    }

                    select {
                    case <-s.stop:
                        unsubscribe <- id
                    case s.events <- e:
                    case <-time.After(time.Second):
                    }
            }
Joey Yi Zhao
  • 37,514
  • 71
  • 268
  • 523
  • 3
    The first snippet creates a separate goroutine for each subscriber, all running concurrently. The second doesn't, and processes each subscriber one by one. – Burak Serdar Jan 03 '23 at 06:28
  • Does this answer your question? [Go goroutine under the hood](https://stackoverflow.com/questions/73562498/go-goroutine-under-the-hood) – Erwin Bolwidt Jan 03 '23 at 09:42

1 Answers1

1

In your first example, that is an anonymous function with the go keyword causing it to function as a goroutine, which is a concurrency pattern in Go. So the code inside the anonymous function (the goroutine) will all process concurrently.

In your second example, excluding the goroutine means the code will run sequentially.

An anonymous function is a function which doesn’t contain any name. It is often used when you want to create an inline function. It can form a closure. An anonymous function is also known as a function literal.

Highway of Life
  • 22,803
  • 16
  • 52
  • 80