duankanyi6539 2014-05-09 19:59
浏览 21
已采纳

Go例程可以共享频道所有权吗?

I understand that usually, if I wish to access an out-of-scope variable from a Go routine, it is my responsibility to create a copy to be conceptually owned by the Go routine. Is this also true for channels, or are those exempt?

Effective Go #channels explains this with the words "it may seem odd to write req := req but it's a [sic] legal and idiomatic in Go to do this," referring to this code example:

var sem = make(chan int, MaxOutstanding)
// (other code, filling sem, defining process(..), etc., omitted)

func Serve(queue chan *Request) {
    for req := range queue {
        <-sem
        req := req // Create new instance of req for the goroutine.
        go func() {
            process(req)
            sem <- 1
        }()
    }
}

I happened to have very nearly replicated this example code in my own project (except that I am using a chan struct{} rather than chan int for my semaphore, and declare it local to the Serve func). Staring at it, I am wondering if accessing the same channel from multiple concurrent goroutines is really fine, or if something like sem := sem is called for.

  • 写回答

2条回答 默认 最新

  • duanneng2014 2014-05-09 20:08
    关注

    Channel accesses are thread-safe, so you do not need to lock it or make local copies of it or anything like that.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型