當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


GO Value用法及代碼示例

GO語言"sync/atomic"包中"Value"類型的用法及代碼示例。

值提供了一致類型值的原子加載和存儲。 Value 的零值從 Load 返回 nil。調用 Store 後,不得複製 Value。

首次使用後不得複製值。

用法:

type Value struct {
    // contains filtered or unexported fields
}

示例(配置):

以下示例展示了如何使用 Value 定期更新程序配置並將更改傳播到工作 goroutine。

package main

import (
	"sync/atomic"
	"time"
)

func loadConfig() map[string]string {
	return make(map[string]string)
}

func requests() chan int {
	return make(chan int)
}

func main() {
	var config atomic.Value // holds current server configuration
	// Create initial config value and store into config.
	config.Store(loadConfig())
	go func() {
		// Reload config every 10 seconds
		// and update config value with the new version.
		for {
			time.Sleep(10 * time.Second)
			config.Store(loadConfig())
		}
	}()
	// Create worker goroutines that handle incoming requests
	// using the latest config value.
	for i := 0; i < 10; i++ {
		go func() {
			for r := range requests() {
				c := config.Load()
				// Handle request r using config c.
				_, _ = r, c
			}
		}()
	}
}

示例(隻讀):

下麵的例子展示了如何使用copy-on-write idiom 來維護一個可擴展的頻繁讀取但不經常更新的數據結構。

package main

import (
	"sync"
	"sync/atomic"
)

func main() {
	type Map map[string]string
	var m atomic.Value
	m.Store(make(Map))
	var mu sync.Mutex // used only by writers
	// read function can be used to read the data without further synchronization
	read := func(key string) (val string) {
		m1 := m.Load().(Map)
		return m1[key]
	}
	// insert function can be used to update the data without further synchronization
	insert := func(key, val string) {
		mu.Lock() // synchronize with other potential writers
		defer mu.Unlock()
		m1 := m.Load().(Map) // load current value of the data structure
		m2 := make(Map)      // create a new value
		for k, v := range m1 {
			m2[k] = v // copy all data from the current object to the new one
		}
		m2[key] = val // do the update that we need
		m.Store(m2)   // atomically replace the current object with the new one
		// At this point all new readers start working with the new version.
		// The old version will be garbage collected once the existing readers
		// (if any) are done with it.
	}
	_, _ = read, insert
}

相關用法


注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 Value。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。