我是果朗的新手,我正在努力理解goroutines。这是我从中得到的一段代码https://www.golangprograms.com/goroutines.html.
package main
import (
"fmt"
"runtime"
"sync"
"sync/atomic"
)
var (
counter int32 // counter is a variable incremented by all goroutines.
wg sync.WaitGroup // wg is used to wait for the program to finish.
)
func main() {
wg.Add(3) // Add a count of two, one for each goroutine.
go increment("Python")
go increment("Java")
go increment("Golang")
wg.Wait() // Wait for the goroutines to finish.
fmt.Println("Counter:", counter)
}
func increment(name string) {
defer wg.Done() // Schedule the call to Done to tell main we are done.
for range name {
fmt.Println("name:", name)
fmt.Println("Counter in range:", counter)
atomic.AddInt32(&counter, 1)
runtime.Gosched() // Yield the thread and be placed back in queue.
}
}
输出:
name: Golang
Counter in range: 0
name: Java
Counter in range: 1
name: Golang
Counter in range: 2
name: Golang
Counter in range: 3
name: Java
Counter in range: 4
name: Golang
Counter in range: 5
name: Python
Counter in range: 6
name: Java
Counter in range: 7
name: Golang
Counter in range: 8
name: Java
Counter in range: 9
name: Golang
Counter in range: 10
name: Python
Counter in range: 11
name: Python
Counter in range: 12
name: Python
Counter in range: 13
name: Python
Counter in range: 14
name: Python
Counter in range: 15
Counter: 16
我无法理解为什么输出是16。甚至我们只添加了3个goroutines。应该是3号吗?
有人能给我解释一下吗?
谢谢。
我无法理解为什么输出是16。甚至我们只添加了3个goroutines。应该是3号吗?
为什么应该是3?它应该是调用atomic.AddInt32(&counter, 1)
的次数。
那是多少次?您启动了3个goroutine,每个goroutine都有一个循环。递增是在循环中完成的。
环路:
for range name {}
string
上的for range
在string
的符文上迭代。您案例中的名称为Golang
、Java
和Python
。因此,循环体的执行次数与这些字符串的符文数量一样多:Golang
为6,Java
为4,Python
为6,加起来为16。
您是给定输入字符串的范围,trange将其视为数组并对其进行迭代。参见此示例
package main
import (
"fmt"
)
func main() {
increment("test")
increment("test_dev")
increment("test_deploy")
}
func increment(name string) {
for i, value := range name {
fmt.Printf("name: %s index: %d, char: %cn", name, i, value)
}
}