go语言求素数详解(带详细数据流图解读)

先贴源代码sieve1.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"

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

// Copy the values from channel 'in' to channel 'out',
// removing those divisible by 'prime'.
func filter(in, out chan int, prime int) {
	for {
		i := <-in // Receive value of new variable 'i' from 'in'.
		if i%prime != 0 {
			out <- i // Send 'i' to channel 'out'.
		}
	}
}

// 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.Print(prime, " ")
		ch1 := make(chan int)
		go filter(ch, ch1, prime)
		ch = ch1
	}
}

两个函数分析

generate函数往ch中传入数据

filter函数从in中接受数据,然后如果不能被prime整除,就传入out

 

由于for语句中,含有协程,为方便理解,可以这样改编源代码:sieve2.go

 


package main

import "fmt"


func main() {
	ch := make(chan int) // Create a new channel.
	go func(ch chan int) {
		for i := 2; ; i++ {
			ch <- i // Send 'i' to channel 'ch'.
		}
	}(ch)      // Start generate() as a goroutine.
	for {
		prime := <-ch
		fmt.Print(prime, " ")
		ch1 := make(chan int)
		go func(in, out chan int, prime int) {
			for {
				i := <-in // Receive value of new variable 'i' from 'in'.      3


				if i%prime != 0 {
					out <- i // Send 'i' to channel 'out'.
				}
			}
		}(ch, ch1, prime)
		ch = ch1
	}
}

for函数注意点:

1.每次迭代都会新建一个prime

2.每次迭代都会新建一个ch1,

3.迭代都会新建一个协程go func(in,out chan int, prime int)  ,也就是此类型协程会增加,且一直运行,起初三个协程,主协程,go func(ch chan int)协程和go func(in,out chan int, prime int) 协程。每次for迭代增加一个go func(in,out chan int, prime int) 协程。

4.通道ch只有一个

数据通道传输问题,先贴图,原图感觉没说清楚,这里新画了一张图,数据流图1:

流程分析:

将go func(in, out chan int, prime int)协程命名为协程A1,也就是第一个方块,这里每次for迭代都会新建一个协程,分别为A2,A3,A4,A5...等。图中未标出

对于A1来说,in通道会接受go func(ch chan int)产生的数据(原来的数字2被prime0接受并输出),为3,4,5,6,7,8,9....

out通道会依次获得in通道中被prime0也就是数字2不能整除的数字,也就是3,5,7,9,11,13,15...

A1如何与A2通信呢

for迭代的末尾  有语句 ch = ch1,也就是依次将A1中out通道的数据通过ch1传给ch, 第二次迭代同样,将首位数字3赋值给peime1并输出,也就是说 5,7,9,11,13,15....等依次传入A2协程中的in通道,然后A2协程从in中找到被3 不能整除的数字,5,7,9,11,13,17,19,12,15,输出5,再将 7,11,13,17,19,,23,25传入A3中的in通道中。。。

for迭代总结:每次迭代都会将上次一迭代中产生的最小的数输出,然后剩下的传入此次迭代新建的协程in通道中。

这里题主是从协程整体数据流分析的,从宏观上看,这些协程会一直运行,并且协程数还会增加,然后进行数据交互。

最后,贴出动画图,

不过这种图是画给懂的人看的,这里难点就是理解各协程间通道交互。

  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值