Get the App
SLTechnology News&Howtos  ›  Servers  › 

What is another way to play with golang value concurrency security

Shulou Source: shulou.com Published: 2022-06-01 06:58:07 09月19日 Update

This article is to share with you about golang value concurrency security is another way to play, the editor feels very practical, so share with you to learn, I hope you can learn something after reading this article, say no more, follow the editor to have a look.

Another way to play with golang value concurrency security is to use atomic.Value and look at a piece of code.

Package mainimport ("sync"sync/atomic"time") func main () {var m atomic.Value type Map map [string] string m.Store (make (Map)) var mu sync.Mutex read: = func (key string) (val string) {M1: = m.Load (). (Map) return M1 [key]} insert: = func (key Val string) {mu.Lock () defer mu.Unlock () M1: = m.Load (). (Map) m2: = make (Map) for k V: = range M1 {m2 [k] = v} m2 [key] = val m.Store (m2)} go func () {for {insert ("k") "v") time.Sleep (100 * time.Millisecond)}} () go func () {for {read ("k")}} () time.Sleep (10 * time.Second)}

Compared with read-write locks, there is less scramble for locks, but relatively, it brings some memory overhead, which is suitable for situations where there are more reads and less writes and variables do not take up a lot of memory. If you use memory to store a large amount of data, this is not suitable. Technically, it is mainly the common copy-on-write.

In addition, this storage is more suitable for program configuration, posting an official chestnut.

Var config 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 Go func + {for r: = range requests () {c: = config.Load () / / Handle request r using config c. _, _ = r, c}} ()}

Yeah, it was fun.

The above is another way to play with golang value concurrency security. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Tags: Security play memory that is more knowledge articles storage fun practical code variables official work meetings common overhead situations technology data articles Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL OPPO Reno Apple macOS Linux