码迷,mamicode.com
首页 > 编程语言 > 详细

go语言怎样开多进程图文讲解。

时间:2015-03-20 14:32:34      阅读:320      评论:0      收藏:0      [点我收藏+]

标签:

今天给大家讲解下go语言开多进程。

package main

import (
    "fmt"
    "time"
)

var c chan int

func main() {
    c = make(chan int)
    go waiting("coffee", 1)
    go waiting("tea", 2)
    fmt.Println("I,am waiting")
    //time.Sleep(3 * time.Second)
    <-c
    <-c
}

func waiting(w string, sec int) {

    time.Sleep(time.Duration(sec) * time.Second)
    fmt.Println(w, "is ready")
    c <- 1
}

如果进程开的比较多,怎样去避免去写多个结束进程的channel,下面我来给大家发下改进版:

package main

import (
    "fmt"
    "time"
)

var c chan int

func main() {
    c = make(chan int)
    go waiting("coffee", 1)
    go waiting("tea1", 2)
    go waiting("tea2", 3)
    go waiting("tea3", 4)
    go waiting("tea4", 5)
    go waiting("tea5", 6)
    go waiting("tea6", 7)
    fmt.Println("I,am waiting")
    //time.Sleep(3 * time.Second)
    i := 0
L:
    for {
        select {
        case <-c:
            i++
            if i > 6 {
                break L
            }
        }
    }
}

func waiting(w string, sec int) {

    time.Sleep(time.Duration(sec) * time.Second)
    fmt.Println(w, "is ready")
    c <- 1
}

go语言怎样开多进程图文讲解。

标签:

原文地址:http://blog.csdn.net/guoer9973/article/details/44489551

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