1、使用chanel
  1. func main() {

  2. done := make(chan bool)

  3. ticker := time.NewTicker(time.Millisecond * 1000)

  4. go func() {

  5. total := 0

  6. for t := range ticker.C {

  7. fmt.Println("Tick at:", t)

  8. total += 1

  9. if total > 10 {

  10. break

  11. }

  12. }

  13. done <- true

  14. }()

  15. <-done

  16. ticker.Stop()

  17. }

2 、使用waigroup
  1. func main() {

  2. var wg sync.WaitGroup

  3. wg.Add(1)

  4. ticker := time.NewTicker(time.Millisecond * 1000)

  5. go func() {

  6. total := 0

  7. for t := range ticker.C {

  8. fmt.Println("Tick at:", t)

  9. total += 1

  10. if total > 10 {

  11. break

  12. }

  13. }

  14. wg.Done()

  15. }()

  16. wg.Wait()

  17. ticker.Stop()

  18. }

复制代码

本文来自:博客园

查看原文:golang协程进行同步方法返回搜狐,查看更多