Concurrence

曹小恒 · · 560 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

goroutine is the core of Go's concurrence

package main
import (    "fmt"    "runtime")
func say(s string)
{    for i := 0;i<5;i++{        
    runtime.Gosched()       
    fmt.Println(s)    
}
}
func main()
{    go say("world")    say("hello")}

Here is the output

// hello// world// hello// world// hello// world// hello// world// hello
  • runtime.Gosched() means letting CPU give out the controling right, resume next time.

channels

channel is a great mechanism for sharing the memories.

establish a channel:

ci := make(chan int)cs := make(chan string)cf := make(chan interface{})

channel receive and send data by <-

ch <- v    //send v to channel chv := <-ch    //receive data from ch and assign to v

Here is an example:

package mainimport "fmt"func sum(a []int,c chan int){    total := 0    for _, v := range a{        total += v    }    c <- total }func main(){    a := []int{3,25,6,4,8,1}    c := make(chan int)    go sum(a[:len(a)/2],c)    go sum(a[len(a)/2:],c)    x,y := <-c,<-c    fmt.Println(x,y,x+y)}

Blockage:

When reading from the channel(value <- chan), it will get blocked till its data got received.

When sending data (ch <- 5) to the channel, it will get blocked till data get read.

No explicit locks are needed.

Non-buffer character makes the concurrence more effective.

Buffered channels

The golang also permmits your assigning buffer's space:

ch := make(chan type, value)
package mainimport "fmt"func main(){    c := make(chan int,2)    c <- 1    c <- 2    fmt.Println(<-c)    fmt.Println(<-c)}

The output should be :

12

First in, first out.

Range and close

package mainimport(    "fmt")func fibonacci(n int, c chan int){    x,y := 1,1    for i := 0;i<n;i++{        c <- x        x,y = y,x+y    }    close(c)    //close the channel}func main(){    c := make(chan int,10)    go fubonacci(cap(c),c)    //cap(c) means the capacity of this channel    for i := range c{        fmt.Println(i)    }}

Select

We can use select to monitor the data flow on one interested channel.

package mainimport "fmt"func fibonacci(c,quit chan int){    x, y := 1,1    for {        select {            case c <- x:                x, y = y, x+y            case c <- quit:                fmt.Println("quit")                return        }    }}func main(){    c := make(chan int)    quit := make(chan int)    go func() {        for i := 0;i<10;i++{            fmt.Println(<-c)        }        quit <- 0    }()    fibnacci(c,quit)}

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

本文来自:简书

感谢作者:曹小恒

查看原文:Concurrence

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

560 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传