【发布时间】:2020-09-03 13:35:52
【问题描述】:
我有 2 个模块(模块 1 和模块 2),我在模块 1 中生成一些随机数,并通过 main 中定义的通道将它们传递给模块 2。当值落在模块 2 中时,我希望它在循环中打印,直到新值再次从模块 1 到达。这是代码。
main.go文件内容
package main
import (
"time"
"example/module1"
"example/module2"
)
func main() {
ints := make(chan []int, 1)
for {
select {
case <- time.After(5 * time.Second):
go module1.GenerateRandint(ints)
case <- module2.Done:
go module2.Start(ints)
}
}
}
module1的内容如下。
package module1
import (
"math/rand"
"time"
)
func GenerateRandint(a chan []int){
var rint []int
for i:=0;i<1;i++ {
rand.Seed(time.Now().UnixNano())
rint = append(rint, rand.Int())
}
a <- rint
}
module2 是:
package module2
import (
"fmt"
"math/rand"
"sync"
"time"
)
var Done = make(chan struct{})
var quit = make(chan struct{})
type localData struct {
nums []int
Lock sync.RWMutex
}
var store localData
func init() {
go func() {
Done <- struct{}{}
quit <- struct{}{}
}()
go printer(0, quit)
}
func printer(id int, quit chan struct{}) {
for {
select {
case <-quit:
return
default:
store.Lock.RLock()
fmt.Println("ID:", id, "====", store.nums)
time.Sleep(500 * time.Millisecond)
store.Lock.RUnlock()
}
}
}
func Start(a chan []int) {
rand.Seed(time.Now().UnixNano())
d := <-a
fmt.Println("RECEIVED DATA", d)
store.Lock.Lock()
go func() {
quit <- struct{}{}
}()
store.nums = d
store.Lock.Unlock()
go printer(rand.Int(), quit)
Done <- struct{}{}
}
在最终输出中,我没有看到printer 函数连续打印切片。它打印一次。我在下面粘贴一个示例输出。
ID: 0 ==== []
RECEIVED DATA [5183630848712612481]
ID: 2057228961822266542 ==== [5183630848712612481]
RECEIVED DATA [7203870927705193095]
RECEIVED DATA [1478549829208931483]
ID: 2311909806311895805 ==== [1478549829208931483]
RECEIVED DATA [3000658591728341557]
理想的输出应该是:
ID: 0 ==== []
RECEIVED DATA [5183630848712612481]
ID: 2057228961822266542 ==== [5183630848712612481]
ID: 2057228961822266542 ==== [5183630848712612481]
ID: 2057228961822266542 ==== [5183630848712612481]
ID: 2057228961822266542 ==== [5183630848712612481]
ID: 2057228961822266542 ==== [5183630848712612481]
RECEIVED DATA [7203870927705193095]
ID: 3052382001843759201 ==== [7203870927705193095]
ID: 3052382001843759201 ==== [7203870927705193095]
ID: 3052382001843759201 ==== [7203870927705193095]
ID: 3052382001843759201 ==== [7203870927705193095]
ID: 3052382001843759201 ==== [7203870927705193095]
RECEIVED DATA [1478549829208931483]
ID: 3850200927174591249 ==== [1478549829208931483]
ID: 3850200927174591249 ==== [1478549829208931483]
ID: 3850200927174591249 ==== [1478549829208931483]
ID: 3850200927174591249 ==== [1478549829208931483]
ID: 3850200927174591249 ==== [1478549829208931483]
RECEIVED DATA [3000658591728341557]
【问题讨论】: