我在 Go 中解決了一個(gè)難題,它通過旋轉(zhuǎn) ASCII 字節(jié)值以匹配行方式(左->右)或列方式(頂部->底部)的字符串,在 2D 字節(jié)數(shù)組中找到一個(gè)字符串。我能夠按順序解決它,當(dāng)它同時(shí)解決它時(shí),我嘗試啟動(dòng)一個(gè) go-routine 來處理特定的輸入組合,看看是否有任何可能的 25 個(gè)旋轉(zhuǎn)可以找到匹配項(xiàng)。代碼摘要如下該FindByConcurrentRot方法采用 2D 字符數(shù)組輸入并嘗試在各種可能的輸入組合中找到字符串的匹配項(xiàng)。問題是 - 下面使用的并發(fā)方法是否有效?如何改進(jìn)?將順序例程“按原樣”轉(zhuǎn)換為并發(fā)程序的方法是否錯(cuò)誤?即是否應(yīng)該重寫整個(gè)程序以充分利用并發(fā)特性?// 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
如何對多個(gè) goroutine 共享的數(shù)據(jù)結(jié)構(gòu)執(zhí)行并發(fā)操作
慕田峪7331174
2022-11-08 16:55:48