我打算同時從多個 goroutine 填充多個 firebird 數據庫,為了做到這一點,我的worker函數有一個 map ( dbConnections),它保存到數據庫的連接(將數據庫的名稱映射到連接):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... // ...}問題是,當我worker僅將函數作為 1 個 goroutine 運行時,一切正常,但是一旦我增加 goroutine 的數量,似乎dbConnections其他 goroutine 會變得混亂,并且 sql 執行會抱怨插入到不存在的表中!我怎樣才能dbConnections以這樣的方式創建每個 goroutine 都有自己獨特的版本?
1 回答

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