Go简单的方法来创建多线程 (multi-gopher) 程序

下面展示一些 示例代码

Goroutines
func main(){
	theMine := [5]string{"rock", "ore", "ore", "rock", "ore"}
	go findOre(theMine)
	go findOre2(theMine)
	<-time.After(time.Second * 5)
}
func findOre(s [5]string){
	for _,v := range s{
		fmt.Println("ore1",v)
	}
}
func findOre2(s [5]string){
	for _,v1 := range s{
		fmt.Println("ore2",v1)
	}
}
Channels
func main() {
	theMine := [5]string{"ore1", "ore2", "ore3"}
	oreChan := make(chan string)


	// Finder
	go func(mine [5]string) {
		for _, item := range mine {
			oreChan <- item //send
		}

	}(theMine)
	fmt.Println(oreChan)
	// Ore Breaker
	go func() {
		for i := 0; i < 3; i++ {
			foundOre := <-oreChan //receive
			fmt.Println("Miner: Received " + foundOre + " from finder")
		}
	}()
	<-time.After(time.Second * 1)
}

Unbuffered Channels
func main() {
	bufferedChan := make(chan string, 4)

	go func() {
		bufferedChan <-"first"
		fmt.Println("Sent 1st")
		bufferedChan <-"second"
		fmt.Println("Sent 2nd")
		bufferedChan <-"third"
		fmt.Println("Sent 3rd")
	}()

	<-time.After(time.Second * 1)

	go func() {
		firstRead := <- bufferedChan
		fmt.Println("Receiving..")
		fmt.Println(firstRead)
		secondRead := <- bufferedChan
		fmt.Println(secondRead)
		thirdRead := <- bufferedChan
		fmt.Println(thirdRead)
	}()
	<-time.After(time.Second * 1)
}
goroutines 和 channels 
func main() {
	theMine := [5]string{"rock", "ore", "ore", "rock", "ore"}
	oreChannel := make(chan string)
	minedOreChan := make(chan string)

	// Finder
	go func(mine [5]string) {
		for k, item := range mine {
			if item == "ore" {
				fmt.Println("ore position:", k)
				oreChannel <- item //send item on oreChannel
			}
		}
	}(theMine)

	// Ore Breaker
	go func() {
		for i := 0; i < 3; i++ {
			foundOre := <-oreChannel //read from oreChannel
			fmt.Println("From Finder:", foundOre)
			minedOreChan <-"minedOre" //send to minedOreChan
		}
	}()

	// Smelter
	go func() {
		for i := 0; i < 3; i++ {
			minedOre := <-minedOreChan //read from minedOreChan
			fmt.Println("From Miner:", minedOre)
			fmt.Println("From Smelter: Ore is smelted")
		}
	}()

	<-time.After(time.Second * 3) // Again, you can ignore this
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值