go channel puzzle

Keith · 2015-08-25 15:53:07 · 1519 次点击 · 大约8小时之前 开始浏览    置顶
这是一个创建于 2015-08-25 15:53:07 的主题,其中的信息可能已经有所发展或是发生改变。

What's the difference between unbuffered channel and buffered channel? For example, arr1 := make(chan string), arr2 := make(chan string, 10), What's the difference? Espacially when using goroutine?

test1:

func main() { c1 := make(chan int)
for i := 0; i < 2 ; i++ {
c1 <- i+1 }
for i := 0; i < 2 ; i++ {
fmt.Println(<-c1) } }

test2:

func main() { c1 := make(chan int)
for i := 0; i < 2 ; i++ {
go func(i int){c1 <- i}(i)
}
for i := 0; i < 2 ; i++ {
fmt.Println(<-c1) } }

Why test1 will cause deadlock and test2 won't?

test3:

func main() { c1 := make(chan int, 2)
for i := 0; i < 2 ; i++ {
c1 <- i+2 go func(i int){c1 <- i}(i)
}
for i := 0; i < 4 ; i++ {
fmt.Println(<-c1) } }

Why test3 outputs "2310" rather than "2301"?

test4

func main() { c1 := make(chan int, 4)
for i := 0; i < 4 ; i++ {
go func(i int){c1 <- i}(i)
}
for i := 0; i < 4 ; i++ {
fmt.Println(<-c1) } }

Why test4 outputs "3012" rather than "0123"?


有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1519 次点击  
加入收藏 微博
2 回复  |  直到 2015-08-27 05:52:09
ikaros
ikaros · #1 · 9年之前

it's like a queue. arr1 := make(chan string) you can put max one member into this chan,in order to push another one ,you should pop it first! arr2 := make(chan string, 10) you can push 10 member ,before you push 11th you should pop some member

the number means max n in the chan at the same time.

ikaros
ikaros · #2 · 9年之前

for the print order.
when you use goroutine,it's hard to say which goroutine will finish first. that's why sometime we use channel to make few goroutine in a order. you can use more goroutine in your test4 and run it few time ,then you can see order not always the same

here a example use channel as lock

package main

import (
    "fmt"
    "time"
)

var c1 chan int

func step1() {
    fmt.Println("step 1")
    c1 <- 1
}

func step2() {
    <-c1
    fmt.Println("step 2")
}
func main() {
    c1 = make(chan int)
    go step2()
    go step1()
    time.Sleep(10)
}
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传