This is a creation in Article, where the information may have evolved or changed.
In Java and other code, we query the operation of the database:
sql = "SELECT * From ...";
result = Db.query (SQL)
For (item in result)
{
.....
}
But in the go language, this is a little bit of dirt, and we can use the nature of the channel's innate queue and thread synchronization. This is also the obvious thinking difference between go and other languages.
The package of DB:
Package Main
var database *db
Type db struct {
Req Chan string
Res Chan interface{}
}
Func init () {
Database = newdb ()
Go database. Run ()
}
To process the query request, please req the SQL in the channel, and the results are placed in the RES channel after executing the query.
Func (d *db) Run () {
var s string
for {
s = <-d.req
D.res <-D.query (s)
}
}
Func (d *db) query (SQL string) interface{}{
//...
}
Func newdb () *db {
Out: = new (db)
Out.req = Make (Chan string)
Out.res = Make (chan bool)
Return out
}
When called, puts SQL into the request queue and blocks the wait response result
sql: = "SELECT * From ...";
if Database.req <-SQL; Res<-database.res {
Use res
}
The benefits of doing so:
1, achieve the synchronous get results, and directly in a thread call method effect is similar.
2. Call and be called in the independent coprocessor thread
3. The query list is a FIFO queue