golang函数如何控制goroutine的执行?
时间:2024-05-04
浏览:323
作者:佚名
编程并不是一个机械性的工作,而是需要有思考,有创新的工作,语法是固定的,但解决问题的思路则是依靠人的思维,这就需要我们坚持学习和更新自己的知识。今天golang学习网就整理分享《golang函数如何控制goroutine的执行?》,文章讲解的知识点主要包括,如果你对Golang方面的知识点感兴趣,就不要错过golang学习网,在这可以对大家的知识积累有所帮助,助力开发能力的提升。
Go 函数控制 Goroutine 执行有以下方式:runtime.Goexit():强制终止当前 Goroutine。sync.WaitGroup: 等待一组 Goroutines 完成。select{}:允许 Goroutine 等待多个事件之一并根据第一个触发的事件执行相应操作。context.Context: 可以用来向 Goroutine 传递截止日期或取消请求。

Go 函数如何控制 Goroutine 的执行
Go 编程语言支持并发,并使用 Goroutine(轻量级线程)实现并发。Goroutine 可以通过函数创建,并在创建后的任何时候启动。本文将介绍用于控制 Goroutine 执行的不同函数,并提供一些实战案例。
控制 Goroutine 执行的函数
- runtime.Goexit():强行终止当前 Goroutine。
- sync.WaitGroup: 等待一组 Goroutines 完成。
- select{}:允许 Goroutine 等待多个事件之一并根据第一个触发的事件执行相应操作。
- context.Context: 可以用来向 Goroutine 传递截止日期或取消请求。
实战案例
1. 终止 Goroutine
package main
import (
"fmt"
"runtime"
"time"
)
func main() {
go func() {
for {
fmt.Println("Goroutine is running...")
time.Sleep(1 * time.Second)
}
}()
// 等待 10 秒后终止 Goroutine
time.Sleep(10 * time.Second)
runtime.Goexit()
}2. 使用 sync.WaitGroup 等待 Goroutine
package main
import (
"fmt"
"sync"
"time"
)
func main() {
var wg sync.WaitGroup
// 创建 5 个 Goroutine
for i := 0; i < 5; i++ {
wg.Add(1)
go func(i int) {
fmt.Printf("Goroutine %d is running...\n", i)
time.Sleep(1 * time.Second)
wg.Done()
}(i)
}
// 等待所有 Goroutine 完成
wg.Wait()
}3. 使用 select{} 响应事件
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("Waiting for events...")
// 创建两个 channel
ch1 := make(chan string)
ch2 := make(chan string)
// 创建两个 Goroutine 向 channel 发送数据
go func() {
time.Sleep(1 * time.Second)
ch1 <- "Event from Channel 1"
}()
go func() {
time.Sleep(2 * time.Second)
ch2 <- "Event from Channel 2"
}()
for {
select {
case msg := <-ch1:
fmt.Println(msg)
return
case msg := <-ch2:
fmt.Println(msg)
return
}
}
}4. 使用 context.Context 取消 Goroutine
package main
import (
"context"
"fmt"
"time"
)
func main() {
// 创建一个 context
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// 创建一个 Goroutine
go func() {
for {
select {
case <-ctx.Done():
fmt.Println("Goroutine cancelled")
return
default:
fmt.Println("Goroutine is running...")
time.Sleep(1 * time.Second)
}
}
}()
// 等待 15 秒后取消 Goroutine
time.Sleep(15 * time.Second)
cancel()
}以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
