简单的用go协程统计8000内的素数

package main

import (
	"time"
	"fmt"
)

//向管道放入80000个数
func createData(size int, intDataChan chan int)  {
	if size < 1 {
		return
	}

	for i := 1; i <= size; i++ {
		intDataChan <- i
	}

	close(intDataChan)
}

func getSuShu(intDataChan chan int, primeChan chan int, exitChan chan bool)  {

	var flag bool
	for {
		time.Sleep(time.Millisecond * 10)
		num, ok := <- intDataChan
		if !ok {//取不到数据
			break
		}
		flag = true //假设是素数
		for i := 2; i <= num /2; i++{
			if num % i == 0 {
				flag = false //确定不是素数
				break
			}
		}

		if flag {
			primeChan <- num
		}
	}

	fmt.Println("\n 有一个协程取不到数据,退出")

	exitChan <- true //标记退出
}

func main() {
	var maxInt  = 8000
	intDataChan := make(chan int, 1000)
	primeChan := make(chan int, maxInt / 3)
	exitChan := make(chan bool, 4)

	go createData(maxInt, intDataChan)

	for i := 0; i < 4; i++ {
		go getSuShu(intDataChan, primeChan, exitChan)
	}

	go func() {
		for i := 0; i < 4; i++ {
			<- exitChan //阻塞直到四个协程都完成工作
		}

		close(primeChan)//关闭管道
	}()

	for {
		res, ok := <- primeChan
		if !ok {
			break
		}

		fmt.Print(res, "  ")
	}
}
posted @ 2019-07-14 14:59  hirampeng  阅读(293)  评论(0编辑  收藏  举报