goroute程序之间通过channel管道通讯

管道通讯方式可以采取,1.全局变量,2.传参

一:全局变量

package main

import (

"fmt"

"time"

)

var pipe chan int

func add(a int, b int) int {

var sum int

sum = a + b

time.Sleep(3 * time.Second)

pipe <- sum

return sum

}

func main() {

pipe = make(chan int, 1)

go add(200, 400)

c := <-pipe

fmt.Println("go pipe add(100, 200) = ", c)

}

二、传参

package main

import (

"fmt"

"time"

)

func add(a int, b int, c chan int) int {

var sum int

sum = a + b

time.Sleep(3 * time.Second)

c <- sum

return sum

}

func main() {

pipe := make(chan int, 1)

go add(200, 400, pipe)

c := <-pipe

fmt.Println("go pipe add(100, 200) = ", c)

}