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 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)