现在位置: 首页  >  编程技术  >  Go
《The Way to Go》协程与信道 示例 14.7-sieve1.go 执行分析
0 2138

书中的代码没有执行步骤的输出,看着很绕,加了各步骤的停顿与状态输出,可以从输出信息中摸出执行的规律。(main中的输出并不能反应go协程的真实执行顺序,但是利用信道的阻塞原理和定时延迟,可以基本实现输出信息同步,起码这样对着输出信息看源码可以有参考作用。)

// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.package main
package main

import (
   "fmt"
   "strconv"
   "time"
)

// Send the sequence 2, 3, 4, ... to channel 'ch'.
func generate(ch chan int) {
   for i := 2; ; i++ {
      fmt.Println("set i=",i)
      ch <- i // Send 'i' to channel 'ch'.
      fmt.Println("set over i=",i)
   }
}

// Copy the values from channel 'in' to channel 'out',
// removing those divisible by 'prime'.
func filter(in, out chan int, prime int) {
   for {
      fmt.Println("get i")
      i := <-in // Receive value of new variable 'i' from 'in'.
      fmt.Println("get i=",i)
      if i%prime != 0 {
         fmt.Println("send "+strconv.Itoa(i) + " to out when prime="+strconv.Itoa(prime))
         out <- i // Send 'i' to channel 'out'.
         fmt.Println("send "+strconv.Itoa(i) + " to out when prime="+strconv.Itoa(prime)+", send OK")
      }else{
         fmt.Println(strconv.Itoa(i) +"%"+strconv.Itoa(prime) + "==0")
      }
   }
}

// The prime sieve: Daisy-chain filter processes together.
func main() {
   ch := make(chan int) // Create a new channel.
   go generate(ch)      // Start generate() as a goroutine.
   for {
      prime := <-ch
      fmt.Println("in for :",prime, " ")
      fmt.Println("sleep start")
      time.Sleep(1e9)
      fmt.Println("sleep over")
      ch1 := make(chan int)
      go filter(ch, ch1, prime)

      fmt.Println("ch = ch1 , start sleep")
      time.Sleep(1e9)
      fmt.Println("ch = ch1 , start end")
      ch = ch1
      fmt.Println("ch = ch1 , done")
      time.Sleep(1e9)
      fmt.Println("out for")
   }
}


 评论
 站内搜索