簡體   English   中英

在 Go 中使用由“for”循環創建的通道

[英]Using channels in Go created by a 'for' loop

for循環中創建的通道可以被從該for循環同時運行的子程序互換使用嗎?

偽代碼如下:

for i := range Map {
    channel := make(chan my_type, buff_size)

    go subroutine(Map[i], channel)
}

func subroutine(name valueType, channel channelType) {
    // Stuff here
}

例如,有沒有辦法讓 subroutine(Map[0]) 可以訪問在for循環的另一次迭代期間創建的另一個通道,即子程序的通道 (Map[1])?


背景:我目前正在做一個項目,我必須模擬不同的細胞群。 每個細胞都具有分裂、分化等能力。為了復制真實系統,不同的群體必須彼此同時運行。 問題是我必須在處理不同的人口時插入/刪除特定人口類型的單元格,這就是渠道發揮作用的地方。 我正在考慮同時運行人口,每個人口都有一個關聯的渠道。 這就是為什么我要問我們是否可以使用在不同的 for 循環迭代中創建的通道。


這是我的一些代碼來支持我的上下文描述,並帶有解釋不同元素的注釋。 我已經包含了頻道,但我不知道它是否有效。 我希望它有助於理解我正在嘗試做的事情:

func main() {
    // Where envMap is a map[int]Population and Population is a struct
    envMap := initialiseEnvironment(envSetupInfo)

    // General simulation loop
    for i := 0; i < 10; i++ {
        // Loop to go through all envMap elements in parallel
        for eachKey := range envMap {
            channel := make(chan type)
            go simulateEnv(envMap[eachKey])
        }
    }
}

func simulateEnv(cellPopulation Population, channel chan) {
    // Each Population has a map[int]Cell where Cell is a struct with cell properties
    cellMap := cellPopulation.cellMap

    for eachCell := range cellMap {
        go divisionTransition(eachCell, channel)
    }
}

假設地圖的每個元素都是一個結構,您可以創建一個字段來保存對其他通道的引用。 例如,如果您希望地圖的每個元素都引用上一個頻道,您可以執行以下操作:

// assumes that Map[whatever] is a struct with a "lastChan" field
var lastRef = chan my_type


for i := range Map {
      channel := make(chan my_type, buff_size)
      if(lastRef != nil){
          Map[i].lastChan = lastRef
      }

      go subroutine(Map[i], channel)
      lastRef = channel
}

func subroutine(name valueType, channel channelType) {
    //stuff here can access the previous channel with name.lastChan
}

根據您想要做什么以及您需要訪問哪些頻道,您可能希望使用循環播放,甚至進行多個循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM