我的问题是如何安排每个间隔N运行独立的非阻塞功能。
我最初的方法是使用select语句中的go通道以非阻塞方式接收值,并time.Sleep(N)
在每个函数中使用它来调度调用。
在下面的代码段中,这仅适用于第一次运行;但是,在第一个呼叫之后,它会继续computeY()
重复呼叫,而不会尊重该time.Sleep()
呼叫。
package main
import (
"fmt"
"time"
)
var (
x string = ""
y string = ""
)
func computeY(c chan string) {
time.Sleep(10 * time.Second)
fmt.Println("I'm in Y")
y = "this is Y value"
c <- y
}
func computeX(c chan string) {
time.Sleep(1 * time.Second)
x = "this is X value"
c <- x
}
func main() {
xC := make(chan string)
yC := make(chan string)
for {
go computeX(xC)
go computeY(yC)
select {
case x := <-xC:
fmt.Println(fmt.Sprintf("X: %v, Y: %v", x, y))
case y := <-yC:
fmt.Println(fmt.Sprintf("X: %v, Y: %v", x, y))
}
}
}
您呼叫都computeX
与computeY
循环的每次迭代。
由于computeX
花费1s,因此for
循环每秒迭代一次,并在yC
获得值时额外花费时间。
这意味着,你正在运行go computeY
的t=0s
,t=1s
,t=2s
,等....在第一个终止t=10s
,第二个t=11s
,等等。
如果你想确保你只安排一个computeX
和computeY
在同一时间,你需要改变你的主要沿着线的东西:
go computeX(xC)
go computeY(yC)
for {
select {
case x = <-xC:
fmt.Printf("Finished computeX: X: %v, Y: %v\n", x, y)
go computeX(xC)
case y = <-yC:
fmt.Printf("Finished computeY: X: %v, Y: %v\n", x, y)
go computeY(yC)
}
}
有关代码的其他注意事项:
x
并且y
是全局的,并在computeX
和computeY
x
并且y
fmt.Println(fmt.Sprintf("..."))
只是 fmt.Printf("...\n")
""
,这是默认值本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句