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

贴一段demo代码,演示channel之间的同步

时间:2014-07-16 19:32:52      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   数据   for   

package main

import (
    "fmt"
    "time"
)

func deskGoRoutine(index int, userChannel chan string, deskChannel chan string) {
    for {
        fmt.Println("deskGoRoutine", index)

        select {
        case info := <-userChannel:
            if info == "userMsg" {
                fmt.Println(info)
                deskChannel <- "deskMsg"
            }
        case <-time.After(time.Second):
            fmt.Println("deskGoRoutine", index, "timeout,continue")
            continue
        }
        time.Sleep(time.Second)
    }
}

func userGoRoutine(index int, deskChannel chan string, userChannel chan string) {
    for {
        fmt.Println("userGoRoutine", index)

        select {
        case info := <-deskChannel:
            if info == "deskMsg" {
                fmt.Println(info)
                userChannel <- "userMsg"
            }
        case <-time.After(time.Second):
            fmt.Println("userGoRoutine", index, "timeout,continue")
            continue
        }
        time.Sleep(time.Second)
    }
}

func main() {

    userChannel := make(chan string)
    deskChannel := make(chan string)

    go userGoRoutine(0, deskChannel, userChannel)
    go deskGoRoutine(0, userChannel, deskChannel)

    userChannel <- "userMsg"

    select {}
}

一个gouRoutine对应一个channel,channel用来同步,如果不加timeout,那么goRoutine在收不到想要的channel数据的时候会死锁,只有加上timeout,才会不断的处理,满足我的需求

贴一段demo代码,演示channel之间的同步,布布扣,bubuko.com

贴一段demo代码,演示channel之间的同步

标签:des   style   blog   color   数据   for   

原文地址:http://www.cnblogs.com/ziyouchutuwenwu/p/3837424.html

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