我打算同時從多個 goroutine 填充多個 firebird 數(shù)據(jù)庫,為了做到這一點,我的worker函數(shù)有一個 map ( dbConnections),它保存到數(shù)據(jù)庫的連接(將數(shù)據(jù)庫的名稱映射到連接):func worker() { dbConnections := map[string]*sql.DB {} for dbName, dbFileName := range dbFiles { connection, err := sql.Open("firebirdsql", ("sysdba:master@localhost:3050/" + url.PathEscape(dbsPath + dbFileName))) err = connection.Ping() if err != nil { fmt.Println("Ping failed: ", err.Error() return } else { dbConnections[dbName] = connection fmt.Println(fmt.Sprintf("Connected to the: %v", dbName)) defer dbConnections[dbName].Close() } } // using the connections to populate databases... // ...}問題是,當(dāng)我worker僅將函數(shù)作為 1 個 goroutine 運行時,一切正常,但是一旦我增加 goroutine 的數(shù)量,似乎dbConnections其他 goroutine 會變得混亂,并且 sql 執(zhí)行會抱怨插入到不存在的表中!我怎樣才能dbConnections以這樣的方式創(chuàng)建每個 goroutine 都有自己獨特的版本?
1 回答

慕后森
TA貢獻(xiàn)1802條經(jīng)驗 獲得超5個贊
正如評論部分中的許多人所提到的,問題是因為線程安全firebirdsql
,尤其是在創(chuàng)建新表時。在 and 之間定義一個并mutex
包含 sql 執(zhí)行方法(以便在任何給定時間只有一個 goroutine 可以創(chuàng)建表)解決了這個問題。mutex.Lock()
mutex.Unlock()
- 1 回答
- 0 關(guān)注
- 104 瀏覽
添加回答
舉報
0/150
提交
取消