登录
首页 >  Golang >  Go问答

使用上下文和缓冲通道作为队列的线程安全性疑虑

来源:stackoverflow

时间:2024-02-09 20:09:24 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
}

线程安全吗? 我的逻辑顺利吗?

如果有任何错误,我希望收到反馈

如果有更好的做法,请告诉我。


正确答案


  1. 上下文是线程安全的。 https://go.dev/blog/context

因此,在多个 goroutine 的 go 领域中,线程安全,因为你永远不知道哪些线程(相同/不同)goroutines 正在运行

  1. 通道是线程安全的 - https://go.dev/ref/spec#Channel_types

通道在底层使用互斥体 https://github.com/golang/go/blob/master/src/runtime/chan.go#L51

  1. 有关并发模式,请查看非常好的 Go 博客文章:

今天关于《使用上下文和缓冲通道作为队列的线程安全性疑虑》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>