"how to make a variable thread-safe" Code Answer


synchronized in java is a mean to allow only a single thread to execute a code block (at any given time).

in go there are numerous constructs to achieve that (e.g. mutexes, channels, waitgroups, primitives in sync/atomic), but go's proverb is: "do not communicate by sharing memory; instead, share memory by communicating."

so instead of locking and sharing a variable, try to not do that but instead communicate the result between goroutines e.g. using channels (so you won't have to access shared memory). for details, see the go blog: share memory by communicating.

of course there may be cases when the simplest, direct solution is to use a mutex to protect concurrent access from multiple goroutines to a variable. when this is the case, this is how you can do that:

var (
    mu        sync.mutex
    protectme int

func getme() int {
    me := protectme
    return me

func setme(me int) {
    protectme = me

the above solution could be improved in several areas:

  • use sync.rwmutex instead of sync.mutex, so that the getme() may lock for reading only, so multiple concurrent readers would not block each other.

  • after a (successful) locking it is advisable to unlock using defer, so if something bad happens in the subsequent code (e.g. runtime panic), the mutex will still be unlocked, avoiding resource leaks and deadlocks. although this example is so simple, nothing bad could happen and does not warrant unconditional use of deferred unlocking.

  • it is good practice to keep the mutex close to the data it is ought to protect. so "wrapping" protectme and its mu in a struct is a good idea. and if we're at it, we may also use embedding, so locking / unlocking becomes more convenient (unless this functionality must not be exposed). for details, see when do you embed mutex in struct in go?

so an improved version of the above example could look like this (try it on the go playground):

type me struct {
    me int

func (m *me) get() int {
    return m.me

func (m *me) set(me int) {
    m.me = me

var me = &me{}

func main() {

this solution has another advantage: should you need multiple values of me, it will automatically have different, separate mutexes for each value (our initial solution would require creating separate mutexes manually for each new values).

although this example is correct and valid, may not be practical. because protecting a single integer does not really require a mutex. we could achieve the same using the sync/atomic package:

var protectme int32

func getme() int32 {
    return atomic.loadint32(&protectme)

func setme(me int32) {
    atomic.storeint32(&protectme, me)

this solution is shorter, cleaner and faster. if you're goal is only to protect a single value, this solution is preferred. if the data structure you ought to protect is more complex, atomic may not even be viable, and using a mutex might be justified.

now after showing examples of sharing / protecting variables, we should also give an example what we should aim to achieve to live up to "do not communicate by sharing memory; instead, share memory by communicating."

the situation is that you have multiple concurrent goroutines, and you use a variable where you store some state. one goroutine changes (sets) the state, and another reads (gets) the state. to access this state from multiple goroutines, access must be synchronized.

and the idea is to not have a "shared" variable like this, but instead the state that one goroutine would set, it should "send" it instead, and the other goroutine that would read it, it should be the one the state is "sent to" (or in other words, the other goroutine should receive the changed state). so there is no shared state variable, instead there is a communication between the 2 goroutines. go provides excellent support for this kind of "inter-goroutine" communication: channels. support for channels is built into the language, there are send statements, receive operators and other support (e.g. you can loop over the values sent on a channel). for an intro and details, please check this answer: what are channels used for?

let's see a practical / real-life example: a "broker". a broker is an entity where "clients" (goroutines) may subscribe to receive messages / updates, and the broker is capable of broadcasting messages to subscribed clients. in a system where there are numerous clients that might subscribe / unsubscribe at any time, and there may be a need to broadcast messages at any time, synchronizing all this in a safe manner would be complex. wisely using channels, this broker implementation is rather clean and simple. please allow me to not repeat the code, but you can check it in this answer: how to broadcast message using channel. the implementation is perfectly safe for concurrent use, supports "unlimited" clients, and does not use a single mutex or shared variable, only channels.

also see related questions:

reading values from a different thread

By Yes Kay Selva on January 30 2022

Answers related to “how to make a variable thread-safe”

Only authorized users can answer the Search term. Please sign in first, or register a free account.