登录
首页 >  Golang >  Go问答

我无法观察到在 for 循环内修改的公共变量的变化

来源:stackoverflow

时间:2024-02-11 16:42:22 319浏览 收藏

学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《我无法观察到在 for 循环内修改的公共变量的变化》,以下内容主要包含等知识点,如果你正在学习或准备学习Golang,就都不要错过本文啦~让我们一起来看看吧,能帮助到你就更好了!

问题内容

我有一个公共变量,我们称之为 tpus,我在无限 for 循环中修改这个值,但是当我尝试在 for 循环中以及 for 循环外的 goroutine 中打印 tpus 时,我得到 2 个不同的结果,什么我想要做的是在 goroutine 中得到与在 for 循环中得到的结果相同的结果。

var tpus []string
    
    func tpu_calc(destination string) {
        clusternodes := getclusternodes(destination)
        go func() {
            wg.add(1)
            time.sleep(2 * time.second)
            for {
                time.sleep(150 * time.millisecond)
                //fmt.printf("\n + %e", tpus)
            }
        }()
        for {
            slot := getslot(destination)
            slotleaders := getslotleaders(destination, strconv.formatuint(slot+10, 10))
            for x := 0; x < 80; x++ {
                for z := 0; z < len(clusternodes.result); z++ {
                    if slotleaders[x] == clusternodes.result[z].pubkey {
                        if len(tpus) >= 2 {
                            x := removeindex(tpus, 0)
                            tpus = append(x, clusternodes.result[x].tpu)
                            fmt.printf("\n + %e", tpus)
                        } else {
                            tpus = append(tpus, clusternodes.result[x].tpu)
                        }
                    }
                }
            }
        }
    }

上面代码的结果:

  • [%!e(字符串=136.144.49.213:8004) %!e(字符串=198.55.56.164:8004)]
  • [%!e(字符串=198.55.56.164:8004) %!e(字符串=13.124.174.97:8003)]
  • [%!e(字符串=13.124.174.97:8003) %!e(字符串=185.16.38.73:8003)]
  • [%!e(字符串=185.16.38.73:8003) %!e(字符串=103.28.52.250:8003)]
  • [%!e(字符串=103.28.52.250:8003) %!e(字符串=18.214.103.198:8004)]
  • [%!e(字符串=18.214.103.198:8004) %!e(字符串=185.188.42.43:9003)]
  • [%!e(字符串=185.188.42.43:9003) %!e(字符串=135.181.115.253:8003)]
var Tpus []string
    
    func TPU_Calc(destination string) {
        clusternodes := GetClusterNodes(destination)
        go func() {
            wg.Add(1)
            time.Sleep(2 * time.Second)
            for {
                time.Sleep(150 * time.Millisecond)
                fmt.Printf("\n + %e", Tpus)
            }
        }()
        for {
            slot := GetSlot(destination)
            slotleaders := GetSlotLeaders(destination, strconv.FormatUint(slot+10, 10))
            for x := 0; x < 80; x++ {
                for z := 0; z < len(clusternodes.Result); z++ {
                    if slotleaders[x] == clusternodes.Result[z].Pubkey {
                        if len(Tpus) >= 2 {
                            X := RemoveIndex(Tpus, 0)
                            Tpus = append(X, clusternodes.Result[x].Tpu)
                            //fmt.Printf("\n + %e", Tpus)
                        } else {
                            Tpus = append(Tpus, clusternodes.Result[x].Tpu)
                        }
                    }
                }
            }
        }
    }

上面代码的结果:

  • [%!e(字符串=142.132.248.119:8003) %!e(字符串=3.231.94.117:8004)]
  • [%!e(字符串=142.132.248.119:8003) %!e(字符串=3.231.94.117:8004)]
  • [%!e(字符串=142.132.248.119:8003) %!e(字符串=3.231.94.117:8004)]
  • [%!e(字符串=142.132.248.119:8003) %!e(字符串=3.231.94.117:8004)]
  • [%!e(字符串=142.132.248.119:8003) %!e(字符串=3.231.94.117:8004)]
  • [%!e(字符串=142.132.248.119:8003) %!e(字符串=3.231.94.117:8004)]
  • [%!e(字符串=142.132.248.119:8003) %!e(字符串=3.231.94.117:8004)]

正确答案


var globalvar []string

func main() {
    var mu sync.mutex

    go func() {
        for {
            // block access to a global variable, so that
            // no one can change it outside the goroutine.
            // if it's already locked outside the goroutine,
            // then wait for unlocking.
            mu.lock()

            // some actions with a global variable...
            fmt.printf("%v\n", globalvar)

            // unlocking access to a global variable
            mu.unlock()

            // some code...
        }
    }()

    for i := 0; i < 255; i++ {
        // block access to a global variable.
        // if it's already locked inside the goroutine,
        // then wait for unlocking.
        mu.lock()

        // some actions with a global variable
        globalvar = append(globalvar, "str #"+strconv.itoa(i))

        // unlock access
        mu.unlock()

        // some code...
    }
}

您还可以定义一个带有互斥锁、值和更改其值的方法的特殊结构。像这样的事情:

type TpusContainer struct {
    mu    sync.Mutex
    value []string
}

func (t *TpusContainer) RemoveIndex(i int) {
    t.mu.Lock()
    defer t.mu.Unlock()
    t.value = RemoveIndex(t.value, i)
}

func (t *TpusContainer) Append(elem string) {
    t.mu.Lock()
    defer t.mu.Unlock()
    t.value = append(t.value, elem)
}

func (t *TpusContainer) String() string {
    t.mu.Lock()
    defer t.mu.Unlock()
    return fmt.Sprintf("%v", t.value)
}

var Tpus TpusContainer

func main() {
    go func() {
        for {
            fmt.Printf("%v\n", Tpus)
        }
    }()

    for i := 0; i < 255; i++ {
        Tpus.RemoveIndex(0)
        Tpus.Append("Some string #"+strconv.Itoa(i))
    }
}

就我个人而言,我更喜欢第二种方法。

好了,本文到此结束,带大家了解了《我无法观察到在 for 循环内修改的公共变量的变化》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>