使用上下文和缓冲通道作为队列的线程安全性疑虑
时间:2024-02-09
浏览:387
作者:佚名
一分耕耘,一分收获!既然都打开这篇《使用上下文和缓冲通道作为队列的线程安全性疑虑》,就坚持看下去,学下去吧!本文主要会给大家讲到等等知识点,如果大家对本文有好的建议或者看到有不足之处,非常欢迎大家积极提出!在后续文章我会继续更新Golang相关的内容,希望对大家都有所帮助!
问题内容
我需要创建一个将数据传递给多个消费者的队列。 我可以使用缓冲通道和上下文来实现它吗? 我不确定这是否是线程安全的
这是我正在讨论的示例代码:
package main
import (
"context"
"fmt"
"strconv"
"time"
)
func main() {
runQueue()
}
func runQueue() {
// When the buffer is full
// sending channel is blocked
queue := make(chan string, 10000)
// If there are too few consumer,
// the channel buffer will be full, and the sending channel will be blocked.
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
consumerCount := 5
go runProducer(queue, ctx, cancel)
for i := 0; i < consumerCount; i++ {
go runConsumer(queue, ctx)
}
select {
case <-ctx.Done():
// close channel to let goroutine get ctx.Done()
close(queue)
}
}
func runConsumer(queue chan string, ctx context.Context) {
for {
data := <-queue
select {
case <-ctx.Done():
return
default:
}
fmt.Println(data)
<-time.After(time.Millisecond * 1000)
}
}
func runProducer(queue chan string, ctx context.Context, cancel context.CancelFunc) {
for {
fmt.Println("get data from server")
select {
case <-ctx.Done():
return
default:
}
// dataList will be filled from other server
dataList, err := getSomethingFromServer()
if err != nil {
if err.Error() == "very fatal error" {
cancel()
return
}
fmt.Println(err)
continue
}
select {
case <-ctx.Done():
return
default:
}
for _, el := range dataList {
queue <- el
}
<-time.After(time.Millisecond * 2000)
}
}
func getSomethingFromServer() ([]string, error) {
var newList []string
for i := 1; i < 4; i++ {
newList = append(newList, strconv.Itoa(i))
}
return newList, nil
}
线程安全吗? 我的逻辑顺利吗?
如果有任何错误,我希望收到反馈
如果有更好的做法,请告诉我。
正确答案
- 上下文是线程安全的。 https://go.dev/blog/context
因此,在多个 goroutine 的 go 领域中,线程安全,因为你永远不知道哪些线程(相同/不同)goroutines 正在运行
- 通道是线程安全的 - https://go.dev/ref/spec#Channel_types
通道在底层使用互斥体 https://github.com/golang/go/blob/master/src/runtime/chan.go#L51
- 有关并发模式,请查看非常好的 Go 博客文章:
今天关于《使用上下文和缓冲通道作为队列的线程安全性疑虑》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
站内热门
最新文章
12.02
12.02
12.02
12.02
12.02
12.02
12.02
热门专题
