亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何對多個 goroutine 共享的數據結構執行并發操作

如何對多個 goroutine 共享的數據結構執行并發操作

Go
慕田峪7331174 2022-11-08 16:55:48
我在 Go 中解決了一個難題,它通過旋轉 ASCII 字節值以匹配行方式(左->右)或列方式(頂部->底部)的字符串,在 2D 字節數組中找到一個字符串。我能夠按順序解決它,當它同時解決它時,我嘗試啟動一個 go-routine 來處理特定的輸入組合,看看是否有任何可能的 25 個旋轉可以找到匹配項。代碼摘要如下該FindByConcurrentRot方法采用 2D 字符數組輸入并嘗試在各種可能的輸入組合中找到字符串的匹配項。問題是 - 下面使用的并發方法是否有效?如何改進?將順序例程“按原樣”轉換為并發程序的方法是否錯誤?即是否應該重寫整個程序以充分利用并發特性?// searchResult defines the information needed to pass to identify if a match has been identified during concurrent searchtype searchResult struct {    row   int    col   int    rot   int    found bool}// processSearchResults runs the gorotuine to perform the search for a particular rotation of inputfunc processSearchResults(wg *sync.WaitGroup, iter int, resultChan chan searchResult, table [][]byte, word string) {    // call goroutine end when the function returns    defer wg.Done()    if iter >= 1 {        rotate(table, iter)    }    x, y, match := present(table, word)    if match {        resultChan <- searchResult{row: x, col: y, rot: iter, found: true}        return    }    resultChan <- searchResult{found: false}}// doCopy creates a copy of the original table to passed for each iteration of the concurrent search// This is an EXPENSIVE operation on a goroutine, because of memory copy operations// The copy is needed for the goroutines to have their own control of data and not run into data// races by passing the original data to each of themfunc doCopy(table [][]byte) [][]byte {    copyTable := make([][]byte, len(table))    for i := range table {        copyTable[i] = make([]byte, len(table[i]))        copy(copyTable[i], table[i])    }    return copyTable}此 Go 操場鏈接上的完整 MVCE - https://go.dev/play/p/7YFAsAlFRUw
查看完整描述

1 回答

?
慕碼人2483693

TA貢獻1860條經驗 獲得超9個贊

這種方法很可能會因復制表所花費的周期過多而受到影響。由于每個 goroutine 都在修改表,因此每個 goroutine 都必須獲得一個單獨的副本。


另一種方法是在只讀表的頂部添加一個層,為每個 goroutine 提供修改后的視圖。這并不能保證更好的性能,但它可能比使用多個 goroutine 復制的性能更好。


方法是有一個表格視圖:


type tableView struct {

   inc int

   table [][]byte

}


func (t tableView) get(row,col int) byte {

   v:=t.table[row][col]

   v+=t.inc

   if v>'z' {...}

   return v

}

然后,您初始化并傳遞一個 tableView 實例。


再說一遍:這可能不會像您期望的那樣快,但它可能比表的多個副本執行得更好。您必須測試并查看。


查看完整回答
反對 回復 2022-11-08
  • 1 回答
  • 0 關注
  • 111 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號