登录
首页 >  Golang >  Go问答

atomic.AddInt64()是否需要显式地从主内存获取/更新值?

来源:stackoverflow

时间:2024-02-14 18:36:23 369浏览 收藏

有志者,事竟成!如果你在学习Golang,那么本文《atomic.AddInt64()是否需要显式地从主内存获取/更新值?》,就很适合你!文章讲解的知识点主要包括,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

在下面的代码中使用 atomic.addint64

func main() {

    // number of goroutines to use.
    const grs = 2

    // wg is used to manage concurrency.
    var wg sync.waitgroup
    wg.add(grs)

    // create two goroutines.
    for g := 0; g < grs; g++ {
        go func() {
            for i := 0; i < 2; i++ {
                atomic.addint64(&counter, 1)
            }

            wg.done()
        }()
    }

    // wait for the goroutines to finish.
    wg.wait()

    // display the final value.
    fmt.println("final counter:", counter)
}

或在下面的代码中使用 atomic.loadint64

func writer(i int) {

    // Only allow one goroutine to read/write to the slice at a time.
    rwMutex.Lock()
    {
        // Capture the current read count.
        // Keep this safe though we can due without this call.
        rc := atomic.LoadInt64(&readCount)

        // Perform some work since we have a full lock.
        fmt.Printf("****> : Performing Write : RCount[%d]\n", rc)
        data = append(data, fmt.Sprintf("String: %d", i))
    }
    rwMutex.Unlock()
    // Release the lock.
}

// reader wakes up and iterates over the data slice.
func reader(id int) {

    // Any goroutine can read when no write operation is taking place.
    rwMutex.RLock()
    {
        // Increment the read count value by 1.
        rc := atomic.AddInt64(&readCount, 1)

        // Perform some read work and display values.
        time.Sleep(time.Duration(rand.Intn(10)) * time.Millisecond)
        fmt.Printf("%d : Performing Read : Length[%d] RCount[%d]\n", id, len(data), rc)

        // Decrement the read count value by 1.
        atomic.AddInt64(&readCount, -1)
    }
    rwMutex.RUnlock()
    // Release the read lock.
}

atomic.addint64(&counter, 1)atomic.loadint64(&readcount) 是否确保 counter/readcount 的值始终引用主内存而不是 l1/l2 缓存?


解决方案


恐怕您的想法可能有点错误。

原子内存操作不保证值将被“刷新”到任何内存或从任何内存中“刷新”;它们仅仅保证多个并发操作的 CPU(核心)的内存视图的一致性。

也就是说,如果一个 CPU 执行 atomic.AddInt64(&counter, 1),并且任何其他数量的 CPU 执行 atomic.LoadInt64(&counter),则保证任何读取 CPU 都会加载counter 在第一个 CPU 增加它之前,或之后,但不是中间的中途 - 例如,当整数的第一个 32 位部分更新但另一个部分尚未更新时;任何原子加载都将保证看到或不看到增量,具体取决于其更新的总顺序。

此外,如果两个 CPU 碰巧“同时”发出 atomic.AddInt64(&counter, 1),则保证在最后一个操作完成时,counter 将增大 at至少 2(假设没有其他 CPU 同时原子地递减该计数器)——也就是说,保证不会因某种冲突而丢失增量,并且它们将彼此正确序列化,如果需要,按未指定的顺序。

重申一下,原子操作与一致性有关;他们没有具体说明如何确保这种一致性(无论如何,这将高度依赖于硬件)。

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《atomic.AddInt64()是否需要显式地从主内存获取/更新值?》文章吧,也可关注golang学习网公众号了解相关技术文章。

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