gpt4 book ai didi

pointers - 如何以并行方式传递指针的引用?

转载 作者:数据小太阳 更新时间:2023-10-29 03:09:36 27 4
gpt4 key购买 nike

我正在编写一个机器人来并行运行一些命令并同时并行运行机器人,但我在启动和暂停功能时遇到了问题。

下面我将留下一个我设置的例子。预计其中一个 bot 会继续运行而其他 bot 会停止,但所有 bot 最终都会运行。

有人可以向我解释为什么在使用 startbot() 命令时,它没有得到 bool 值吗?

package main

import (
"log"
"time"
)

type botBase struct {
isEnabled bool
}

func (b *botBase) startFunctionX() {
b.isEnabled = true
}

func (b *botBase) pauseFunctionX() {
b.isEnabled = false
}

func (b botBase) runCommandX() {
for {
if b.isEnabled {
log.Print("running...")
} else {
log.Print("paused...")
}
time.Sleep(1 * time.Second)
}
}

type bot struct {
botBase
//other stuffs
}

func (b bot) runAllCommands() {
go b.runCommandX()

//wait parallels commands
for{
time.Sleep(10 * time.Hour)
}
}

type bots struct {
List []bot
}

func (b *bots) loadListDB() {
b1 := bot{}
b1.isEnabled = false
b2 := bot{}
b2.isEnabled = false
b.List = []bot{b1, b2}
}

var myBots bots

func main() {
myBots.loadListDB()
for _, b := range myBots.List {
b.startFunctionX()
go b.runAllCommands()
}

//control stop and start bots
log.Print("expected true = ", myBots.List[0].isEnabled)
myBots.List[0].pauseFunctionX()
log.Print("expected false = ", myBots.List[0].isEnabled)


//wait bots parallels
for {
time.Sleep(10 * time.Hour)
}
}

最佳答案

range 语句返回机器人的值,然后更改该值,因此您实际上正在检查不同的机器人.. 使用引用 -

for i := range myBots.List {
b := &myBots.List[i]
b.startFunctionX()
go b.runAllCommands()
}

https://play.golang.org/p/1V8tKx431QJ

关于pointers - 如何以并行方式传递指针的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53898588/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com