Atomic Assignment

2,057 views
Skip to first unread message

Shane Turner

unread,
Jan 16, 2014, 10:11:37 AM1/16/14
to golan...@googlegroups.com
I have a program which has a pointer to configuration information. Upon each request, the config information is used to determine how to handle the request.
The program will periodically look for changes in the config file and reload them.  When changes are detected, the configuration object is built up again fresh and then simply reassigned to the
configuration variable.  I was thinking that if I assign this variable atomically, there would be no need for use of RWMutex or anything, however I can' figure out how
to use LoadPointer to get back to my original type to use it.  I'm assuming if I do StorePointer, I should LoadPointer to read it consistently.
Or am I approaching this all wrong?


// quick example with comments

package hello

import (
    "sync/atomic"
    "unsafe"
)

type Config struct {
}

type Server struct {
    Configuration *Config
}

func (server *Server) loadConfig(configFile string) {
    newConfig := new(Config)
    // load config as necessary

    // if I perform atomic assignment of (server.Configuration = newConfig), new config is picked up immediately on next read?
    // is this right?
    currentConfigPtr := unsafe.Pointer(server.Configuration)
    newConfigPtr := unsafe.Pointer(newConfig)
    atomic.StorePointer(&currentConfigPtr, newConfigPtr) 
}

func (server *Server) handleRequest() {
        
    // do I need to read config atomically with LoadPointer?
    // if so, how do I do that.  I've tried several things and 
    // can't figure out how to cast back to my original type

    // or should I use RWMutex to faciliate access to config object?
}


Thanks!
Shane

James Bardin

unread,
Jan 16, 2014, 11:20:03 AM1/16/14
to golan...@googlegroups.com


On Thursday, January 16, 2014 10:11:37 AM UTC-5, Shane Turner wrote:
func (server *Server) handleRequest() {
        
    // do I need to read config atomically with LoadPointer?

I believe this is the case to be safe.

 
    // if so, how do I do that.  I've tried several things and 
    // can't figure out how to cast back to my original type


What have you tried? 
Remember that LoadPointer needs a pointer to a pointer, and return that pointer. 
There's not casting, but you can convert the returned to a Config pointer with (*Config)(pointer)

 
    // or should I use RWMutex to faciliate access to config object?


That may be more straightforward.
You could just embed a sync.Mutex, and have accessor methods that Lock the object.
 

Dmitry Vyukov

unread,
Jan 16, 2014, 11:32:35 AM1/16/14
to Shane Turner, golang-nuts
Yes, it's perfectly fine. You can see an example here:
https://groups.google.com/d/msg/golang-nuts/oouY4JM5ea8/T6217B2fKrYJ
Reply all
Reply to author
Forward
0 new messages