


How to properly close database connections for multiple Goroutine shared in Go language?
Elegant close of Go multi-Goroutine shared database connection
In Go concurrent programming, multiple Goroutine shared database connections are common scenarios. Improper connection shutdown may result in data loss or program crash. This article explores how to safely close database connections for multiple Goroutine shared.
Problem analysis:
Using defer db.Close()
directly in the main Goroutine cannot guarantee that all child Goroutines have completed database operations, which may cause the connection to be closed in advance and raise an error. Using defer db.Close()
in each child Goroutine will cause the connection to be closed multiple times, and the same error will be raised.
Solution:
It is recommended to use counters and sync.WaitGroup
to coordinate the execution of Goroutine and the closing of database connections.
Sample code:
package main import ( "fmt" "sync" "time" "database/sql" _ "github.com/go-sql-driver/mysql" // Replace with your database driver) type dbConn struct { conn *sql.DB wg *sync.WaitGroup } func openDb() (*dbConn, error) { db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/database") // Replace with your database connection string if err != nil { return nil, err } return &dbConn{conn: db, wg: &sync.WaitGroup{}}, nil } func (dc *dbConn) close() error { dc.wg.Wait() // Wait for all Goroutines to complete return dc.conn.Close() } func querydb(dc *dbConn, i int) { defer dc.wg.Done() dc.wg.Add(1) // Counter is added 1 // ... Database operation... time.Sleep(time.Second) // Simulate database operations time-consuming fmt.Printf("Goroutine %d finished\n", i) } func main() { dc, err := openDb() if err != nil { fmt.Println("Error opening database:", err) Return } defer dc.close() // Make sure to close the connection last for i := 0; i <p> <strong>Code explanation:</strong></p><ol> <li> The <code>dbConn</code> structure contains the database connection and <code>sync.WaitGroup</code> to manage the execution of Goroutines.</li> <li> The <code>openDb</code> function opens the database connection and returns <code>dbConn</code> instance.</li> <li> The <code>close</code> method uses <code>dc.wg.Wait()</code> to wait for all Goroutines to complete before closing the database connection.</li> <li> <code>querydb</code> function uses <code>dc.wg.Add(1)</code> to increase the counter before executing the database operation, and uses <code>defer dc.wg.Done()</code> to decrease the counter after the operation is completed.</li> <li> <code>main</code> function starts multiple Goroutines to execute <code>querydb</code> functions, and finally closes the database connection using <code>defer dc.close()</code> .</li> </ol><p> This method ensures that all Goroutines complete database operations and then close the database connection, avoiding data loss and errors. Remember to replace the database connection string and driver in the sample code. If the database operation time is unpredictable, more complex mechanisms may be required to wait for all Goroutines to complete, such as signaling using a channel.</p>
The above is the detailed content of How to properly close database connections for multiple Goroutine shared in Go language?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

Exchanges that support cross-chain transactions: 1. Binance, 2. Uniswap, 3. SushiSwap, 4. Curve Finance, 5. Thorchain, 6. 1inch Exchange, 7. DLN Trade, these platforms support multi-chain asset transactions through various technologies.

Aavenomics is a proposal to modify the AAVE protocol token and introduce token repos, which has implemented a quorum for AAVEDAO. Marc Zeller, founder of the AAVE Project Chain (ACI), announced this on X, noting that it marks a new era for the agreement. Marc Zeller, founder of the AAVE Chain Initiative (ACI), announced on X that the Aavenomics proposal includes modifying the AAVE protocol token and introducing token repos, has achieved a quorum for AAVEDAO. According to Zeller, this marks a new era for the agreement. AaveDao members voted overwhelmingly to support the proposal, which was 100 per week on Wednesday

The steps to draw a Bitcoin structure analysis chart include: 1. Determine the purpose and audience of the drawing, 2. Select the right tool, 3. Design the framework and fill in the core components, 4. Refer to the existing template. Complete steps ensure that the chart is accurate and easy to understand.

Suggestions for choosing a cryptocurrency exchange: 1. For liquidity requirements, priority is Binance, Gate.io or OKX, because of its order depth and strong volatility resistance. 2. Compliance and security, Coinbase, Kraken and Gemini have strict regulatory endorsement. 3. Innovative functions, KuCoin's soft staking and Bybit's derivative design are suitable for advanced users.

The platforms that have outstanding performance in leveraged trading, security and user experience in 2025 are: 1. OKX, suitable for high-frequency traders, providing up to 100 times leverage; 2. Binance, suitable for multi-currency traders around the world, providing 125 times high leverage; 3. Gate.io, suitable for professional derivatives players, providing 100 times leverage; 4. Bitget, suitable for novices and social traders, providing up to 100 times leverage; 5. Kraken, suitable for steady investors, providing 5 times leverage; 6. Bybit, suitable for altcoin explorers, providing 20 times leverage; 7. KuCoin, suitable for low-cost traders, providing 10 times leverage; 8. Bitfinex, suitable for senior play

Cryptocurrency data platforms suitable for beginners include CoinMarketCap and non-small trumpet. 1. CoinMarketCap provides global real-time price, market value, and trading volume rankings for novice and basic analysis needs. 2. The non-small quotation provides a Chinese-friendly interface, suitable for Chinese users to quickly screen low-risk potential projects.

The forecasts for the top 10 formal cryptocurrency trading platforms in the 2025 cryptocurrency trading platforms are: 1. Coinbase, 2. Kraken, 3. Gemini, 4. Binance, 5. Ouyi, 6. Bitstamp, 7. LMAX Digital, 8. Itbit, 9. Coincheck, 10. Sesame Open Door, these platforms perform excellently in compliance, security, user experience, etc.
