Skip to content

[勘误]反馈一个第5章第3节的WaitGroup问题 #45

Description

@stevenlee87

问题描述
go1.16.6
Add()操作必须早于Wait(),否则会触发panic

如何找到这个错误

  • 章节:5
  • 页码:120

您认为应该如何?
go1.16.6版本,Wait早于Add()现在也不会panic了
不知道是不是golang版本的因素

代码

func main() {
	var wg sync.WaitGroup
	wg.Wait() //Wait早于Add()现在也不会panic了
	wg.Add(2) //设置计数器,数值即为goroutine的个数
	go func() {
		time.Sleep(1 * time.Second)

		fmt.Println("Goroutine 1 finished!")
		wg.Done() //goroutine执行结束后将计数器减1
	}()

	go func() {
		time.Sleep(2 * time.Second)

		fmt.Println("Goroutine 2 finished!")
		wg.Done() //goroutine执行结束后将计数器减1
	}()

	wg.Wait() //主goroutine阻塞等待计数器变为0
	fmt.Printf("All Goroutine finished!")
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions