我在探索Go並試圖建立一種使用渠道的管道。我只想在main()中讀取一些內容並將它們發送到process()進行處理,在這種情況下,只需將值輸出到屏幕即可。使用渠道去管道
不幸的是,在下面的代碼中,似乎process()永遠不會從通道讀取數據,或者至少不會打印任何數據;我究竟做錯了什麼?
package main
import ("fmt" ; "database/sql" ; _ "github.com/lib/pq" ; "time" ; "gopkg.in/redis.v3")//; "strconv")
type Record struct {
userId, myDate int
prodUrl string
}
func main(){
//connect to db
db, err := sql.Open(...)
defer db.Close()
//error check here...
//exec query
rows, err := db.Query("select userID,url,date from mytable limit 10")
defer rows.Close()
//error check here...
//create channel to buffer rows read
bufferChan := make(chan *Record,1000)
go process(bufferChan)
//iterate through results and send them to process()
row := new(Record)
for rows.Next(){
err := rows.Scan(&row.userId, &row.prodUrl, &row.myDate)
bufferChan <- row
fmt.Printf("row sent %v",row.userId)
}
}
//prints Record values
func process (buffer chan *Record) {
row := <- buffer
fmt.Printf("row received: %d %v %d ", row.userId,row.prodUrl,row.myDate)
}
謝謝,這個工作,但現在看來,發送和接收順序執行,我是理解錯了?我的目標是讓process()與main()並行執行,並在bufferChan通道可用時使用數據,但似乎main()會執行整個for()循環,然後纔會執行process()開始打印消息。 – derelict
是的,這是因爲只有一次去消耗通道bufferChan上的東西。看看這個例子https://gobyexample.com/worker-pools這就是你如何實現並行處理。 –