码迷,mamicode.com
首页 > 其他好文 > 详细

golang for thread channel routine consumer and producer

时间:2017-05-06 10:24:25      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:style   into   tin   pack   class   code   ++   ack   finish   

package main

import "time"

func testThread(){
    i:=3
    go func(a int){
        println(a)
        println("this is go func!")
    }(i)

    time.Sleep(1*time.Second)
    println("hello main thread!")
}

func testChannel(){
    //read write channel
    ch:=make(chan int,1)
    ch<-3
    go func(){
        v:=<-ch
        println(v)
    }()
    time.Sleep(1*time.Second)
    println("finish chan!")
}

func producer(p chan<-int){
    for i:=0;i<10;i++{
        p<-i
        println("into chan:",i)
    }
    println("finish the producer!")

}

func consumers(c <-chan int){
    for i:=0;i<10;i++{
        v:=<-c
        println("get from channel:",v)

    }
    println("finish the consumers!!")
}

//test producer and consumer
func testProducerConsumer(){
    ch:=make(chan int,1)
    go consumers(ch)
    go producer(ch)
    time.Sleep(2*time.Second)
    println("finish all the consumer and producer!!")
}

func main() {
    //testThread()
    //testChannel()
    testProducerConsumer()
}

 

熟悉语法:chan,go多线程

 

golang for thread channel routine consumer and producer

标签:style   into   tin   pack   class   code   ++   ack   finish   

原文地址:http://www.cnblogs.com/20121207program/p/golang_channel.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!