其他分享
首页 > 其他分享> > Go-waitGroup的那些事

Go-waitGroup的那些事

作者:互联网

上代码, 自己品:

package main

import (
	"fmt"
	"sync"
)

func main() {
	var wg sync.WaitGroup
	wg.Add(2)
	go func() {
		defer wg.Done()
		fmt.Println(1)
	}()
	go func() {
		defer wg.Done()
		fmt.Println(2)
	}()
	wg.Wait()
	fmt.Println("Done")
}
package main

import (
	"fmt"
	"sync"
	"time"
)

func main() {
	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		//defer wg.Done()
		fmt.Println(1)
		wg.Done()
		wg.Add(1)
		time.Sleep(time.Second * 1)
		wg.Done()
	}()
	wg.Wait() // panic: sync: WaitGroup is reused before previous Wait has returned
	fmt.Println("Done")
}
package main

import (
	"fmt"
	"sync"
)

func main() {
	var once sync.Once
	once.Do(
		func() {
			fmt.Println(1)
		},
	)
	once.Do(
		func() {
			fmt.Println(2)
		},
	)
	fmt.Println("Done")
}

/*
1
Done
*/
package main

import (
	"fmt"
	"sync"
)

func main() {
	var once sync.Once

	go func() {
		once.Do(
			func() {
				fmt.Println(1)
			},
		)
	}()

	go func() {
		once.Do(
			func() {
				fmt.Println(2)
			},
		)
	}()

	fmt.Println("Done")
}

/*
Done
*/
package main

import (
	"fmt"
	"sync"
	"time"
)

func main() {
	var once sync.Once

	go func() {
		// 会阻塞
		once.Do(
			func() {
				fmt.Println(2)
			},
		)
		fmt.Println(2, "done")
	}()
	once.Do(
		func() {
			time.Sleep(time.Second * 3)
			fmt.Println(1)
		},
	)
	fmt.Println("Done")

	time.Sleep(time.Second * 5)
}

/*
1
Done
2 done
*/

标签:wg,waitGroup,fmt,sync,那些,Println,Done,func,Go
来源: https://blog.csdn.net/galoiszhou/article/details/122824066