社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
func goExit1() {
var wg sync.WaitGroup
inCh := make(chan int)
wg.Add(1)
go func(in <-chan int, wg *sync.WaitGroup) {
defer wg.Done()
// Using for-range to exit goroutine
// range has the ability to detect the close/end of a channel
for x := range in {
time.Sleep(time.Second * 1)
fmt.Printf("Process %d %d\n", x, runtime.NumGoroutine())
}
}(inCh, &wg)
for i := 0; i < 10; i++ {
inCh <- i
}
close(inCh)
wg.Wait()
fmt.Println("结束")
}
func goExit2() {
var wg sync.WaitGroup
inCh := make(chan int)
quitCh := make(chan int)
wg.Add(1)
go func(in <-chan int, quit <-chan int, wg *sync.WaitGroup) {
defer wg.Done()
for {
select {
case x := <-in:
time.Sleep(time.Second * 2)
fmt.Printf("Process %d %d\n", x, runtime.NumGoroutine())
case <-quit:
time.Sleep(time.Second * 2)
fmt.Println("收到退出信息")
return
}
}
}(inCh, quitCh, &wg)
for i := 0; i < 10; i++ {
inCh <- i
}
quitCh <- 1
close(inCh)
close(quitCh)
wg.Wait()
fmt.Println("结束")
}
func goExit3() {
var wg sync.WaitGroup
inCh := make(chan int)
quitCh1 := make(chan int)
quitCh2 := make(chan int)
wg.Add(1)
go func(wg *sync.WaitGroup, in, quit, quit2 <-chan int) {
defer wg.Done()
for {
select {
case x := <-in:
time.Sleep(time.Second * 2)
fmt.Printf("Process %d %d\n", x, runtime.NumGoroutine())
case _, ok := <-quit:
if !ok {
fmt.Println("收到退出信号")
quit = nil
}
case _, ok := <-quit2:
if !ok {
fmt.Println("收到退出信号")
quit2 = nil
}
}
if quit == nil && quit2 == nil {
return
}
}
}(&wg, inCh, quitCh1, quitCh2)
for i := 0; i < 10; i++ {
inCh <- i
}
quitCh1 <- 1
quitCh2 <- 1
close(inCh)
close(quitCh1)
close(quitCh2)
wg.Wait()
fmt.Println("结束")
}
func context2() {
var wg sync.WaitGroup
// 3*time.Second 表示设置3秒超时,超时后子程序会自动退出。
//ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
ctx, cancel := context.WithCancel(context.Background())
wg.Add(1)
go func(ctx context.Context, wg *sync.WaitGroup) {
defer wg.Done()
for {
select {
case <-ctx.Done():
fmt.Println("ctx.Done()通道退出")
return
default:
fmt.Println("执行默认分支,并休眠1秒")
time.Sleep(time.Second * 1)
}
}
}(ctx, &wg)
time.Sleep(time.Second * 5)
cancel()
wg.Wait()
fmt.Println("主线程结束")
}
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!