create Golang project with channel

1, create new project "test11_channel"

$ cd ~/project
$ mkdir test11_channel
$ cd test11_channel
$ touch channel.go

2,add following lines in “channel.go”

package main

import (
	"fmt"
	"time"
)

func main() {
	// TEST 1, goroutine
	var n1, n2 string = "pang pamg", "nao nao"
	go greet(n1)
	greet(n2)
	// TEST 2, channel
	var chn = make(chan(int), 1)
	var num1 = []int{1, 2, 3, 4, 5}
	var num2 = []int{6, 7, 8, 9, 10}
	go calculate(num1, true, chn)
	go calculate(num2, false, chn)
	var res1, res2 int
	res1 = <- chn
	res2 = <- chn
	fmt.Printf("%T, %v, %T, %v ", res1, res1, res2, res2)
	fmt.Println("total =", res1 + res2)
	// TEST 3, close a channel
	close(chn)
	res, ok := <- chn
	fmt.Println(res, ok)
}

func greet(name string) {
	for i := 0; i < 3; i++ {
		fmt.Println("Hello", name)
		time.Sleep(time.Second)
	}
}
func calculate(nums []int, isfast bool, chn chan int) {
	var res int = 0
	for _, n := range nums {
		res = res + n
		if isfast {
			time.Sleep(time.Second)
		} else {
			time.Sleep(2 * time.Second)
		}
	}
	fmt.Println("finish calculation:", isfast)
	chn <- res
}

3, run “channel.go”

go run channel.go

you should get result like this:

Hello nao nao
Hello pang pamg
Hello nao nao
Hello pang pamg
Hello nao nao
Hello pang pamg
finish calculation: true
finish calculation: false
int, 15, int, 40 total = 55
0 false

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值