douang2297 2018-12-22 19:10
浏览 21
已采纳

如何通过并行传递指针的参考?

I'm writing a bot to run some commands in parallel and at the same time run the bots in parallel, but I'm having trouble starting and pausing functions.

Below I'll leave an example I set up. It was expected that one of the bots would continue to run and others would stop, but all would end up running.

Could someone explain to me why, when using the startbot() command, it does not get 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)
    }
}
  • 写回答

1条回答 默认 最新

  • dscs63759 2018-12-22 19:49
    关注

    the range statement returns the value of a bot which is then changed so you're actually checking a different bot.. work with references -

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

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作