You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

config.go 936B

123456789101112131415161718192021222324252627282930313233
  1. // Copyright (c) 2022 Shivaram Lingamneni
  2. // released under the MIT license
  3. package utils
  4. import (
  5. "sync/atomic"
  6. "unsafe"
  7. )
  8. /*
  9. This can be used to implement the following pattern:
  10. 1. Prepare a config object (this can be arbitrarily expensive)
  11. 2. Take a pointer to the config object and use Set() to install it
  12. 3. Use Get() to access the config from any goroutine
  13. 4. To update the config, call Set() again with a new prepared config object
  14. 5. As long as any individual config object is not modified (by any goroutine)
  15. after it is installed with Set(), this is free of data races, and Get()
  16. is extremely cheap (on amd64 it compiles down to plain MOV instructions).
  17. */
  18. type ConfigStore[Config any] struct {
  19. ptr unsafe.Pointer
  20. }
  21. func (c *ConfigStore[Config]) Get() *Config {
  22. return (*Config)(atomic.LoadPointer(&c.ptr))
  23. }
  24. func (c *ConfigStore[Config]) Set(ptr *Config) {
  25. atomic.StorePointer(&c.ptr, unsafe.Pointer(ptr))
  26. }