Use channel to control synchronization and transfer of data between Goroutins

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.