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

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

Golang 并發 R/W 到數據庫

Golang 并發 R/W 到數據庫

Go
搖曳的薔薇 2022-06-06 17:11:26
我正在編寫一些 Go 軟件,負責下載和解析大量 JSON 文件并將解析后的數據寫入 sqlite 數據庫。我目前的設計有 10 個 go 例程,同時下載/解析這些 JSON 并將它們傳送到另一個 go 例程,該例程的唯一工作是監聽特定頻道并將頻道內容寫入數據庫。系統會在所有寫入完成后執行一些額外的讀取操作,這會導致查詢返回錯誤結果的問題,因為并非所有數據都已寫入表。因為我提取的 JSON 數據是動態的,所以我沒有簡單的方法知道所有數據何時都已寫入。我考慮了兩種解決方案的可能性,盡管我對這兩種解決方案都不太滿意:在頻道上收聽并等待它為空。這原則上應該有效,但是,它不能確保數據已被寫入,它只確保它已在通道上接收到。同步對數據庫的訪問。這在原則上應該再次起作用,但是,我仍然需要將查詢操作放在所有寫操作之后。我是否應該考慮其他任何設計決策來糾正這個問題?作為參考,我用來提取這些數據的庫是 go-colly 和 go-sqlite3。感謝所有的幫助!
查看完整描述

1 回答

?
阿晨1998

TA貢獻2037條經驗 獲得超6個贊

你可以使用一個sync.WaitGroup


例如


package main


import "sync"


func main() {

    // Some sort of job queue for your workers to process. This job queue should be closed by the process

    // that populates it with items. Once the job channel is closed, any for loops ranging over the channel

    // will read items until there are no more items, and then break.

    jobChan := make(chan JobInfo)


    // Populate the job queue here...

    // ...

    close(jobChan)


    // We now have a full queue of jobs that can't accept new jobs because the channel is closed.


    // Number of concurrent workers.

    workerCount := 10


    // Initialize the WaitGroup.

    wg := sync.WaitGroup{}

    wg.Add(workerCount)


    // Create the worker goroutines.

    for i := 0; i < workerCount; i++ {

        go func() {

            // When the jobChan is closed, and no more jobs are available on the queue, the for loop

            // will exit, causing wg.Done() to be called, and the anonymous function to exit.

            for job := range jobChan {

                // Process job.

            }

            wg.Done()

        }()

    }


    // Wait for all workers to call wg.Done()

    wg.Wait()


    // Whatever you want to do after all queue items have been processed goes here.

    // ...

}



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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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