• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

UnderstandingChanChan'sinGo

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

转自老外的文章:http://tleyden.github.io/blog/2013/11/23/understanding-chan-chans-in-go/

 

A channel describes a transport of sorts. You can send a thing down that transport. When using a chan chan, the thing you want to send down the transport is another transport to send things back.

They are useful when you want to get a response to something, and you don’t want to setup two channels (it’s generally considered bad practice to have data moving bidirectionally on a single channel)

Visual time lapse walkthrough

Keep in mind that Goroutine C is the “real consumer” even though it will be the one which writes to the request channel.

The request channel starts out empty.

Goroutine C passes a “response channel” to go routine D via the request channel

Goroutine C starts reading from the (still empty) response channel.

Goroutine D writes a string to the response channel

Goroutine C now is able to read a value from response channel, and get’s the “wassup!” message

And now we are back to where we started

Here is some code that uses chan chan’s

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package main

import "fmt"
import "time"

func main() {

     // make the request chan chan that both go-routines will be given
     requestChan := make(chan chan string)

     // start the goroutines
     go goroutineC(requestChan)
     go goroutineD(requestChan)

     // sleep for a second to let the goroutines complete
     time.Sleep(time.Second)

}

func goroutineC(requestChan chan chan string) {

     // make a new response chan
     responseChan := make(chan string)

     // send the responseChan to goRoutineD
     requestChan <- responseChan

     // read the response
     response := <-responseChan

     fmt.Printf("Response: %v\n", response)

}

func goroutineD(requestChan chan chan string) {

     // read the responseChan from the requestChan
     responseChan := <-requestChan

     // send a value down the responseChan
     responseChan <- "wassup!"

}

This code can be run on Go playground


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Go 开发者进阶周刊(Dec week 4)发布时间:2022-07-10
下一篇:
Go - 类型与变量发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap