golang golang频道测试

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang golang频道测试相关的知识,希望对你有一定的参考价值。

package goroutines

import (
	"fmt"
	"math"
	"time"
)

func putSthToChannel(sth interface{}, c chan interface{}) {
	c <- sth
}

func calcPrime(nl []int, count int, done chan bool) {
Loop:
	for i := 2; i <= count; i++ {
		var j int
		for j = 2; float64(j) <= math.Sqrt(float64(i)); j++ {
			if i%j == 0 {
				continue Loop
			}
		}
		nl = append(nl, i)
	}
	done <- true
}

func calcuPrime2(count int, nl chan int) {
Loop:
	for i := 2; i <= count; i++ {
		var j int
		for j = 2; float64(j) <= math.Sqrt(float64(i)); j++ {
			if i%j == 0 {
				continue Loop
			}
		}
		nl <- i
	}
	close(nl)
}

func CallPut() {
	c := make(chan interface{})
	go putSthToChannel("channel", c)
	v := <-c
	fmt.Println(v)

	go putSthToChannel(1000000, c)
	v = <-c
	fmt.Println(v)

	go putSthToChannel(struct{ a string }{a: "1"}, c)
	v = <-c
	fmt.Println(v)

	go putSthToChannel(time.Now().Unix(), c)
	v = <-c
	fmt.Println(v)
}

func CalcuPrime() {
	nl := []int{}
	c := make(chan bool)
	go calcPrime(nl, 100, c)

	v := <-c
	fmt.Println(v)
	fmt.Println(nl)

	for _, n := range nl {
		fmt.Println(n)
	}
}

func CalcuPrime2(count int) {
	// count := 10
	nl := make(chan int, count)
	go calcuPrime2(count, nl)
	for x := range nl {
		fmt.Println(x)
	}
}

golang Gen频道

package main

func gen() <-chan int {
	out := make(chan int)
	go func() {
		i := 0
		for {
			out <- i
			i++
		}
	}()

	return out
}

以上是关于golang golang频道测试的主要内容,如果未能解决你的问题,请参考以下文章

golang [去阻塞频道]与Go#golang,#go,#go channels,#go synchronization,#goroutines,#waitgroups中的频道同步和阻止,

为啥我的 Golang 频道写入永远阻塞?

Golang频道睡着了

Golang频道发行

golang 合并频道

golang Gen频道