Does Go support volatile / non-volatile variables?

I’m new to the language so bear with me.

I am curious how GO handles data storage available to threads, in the sense that non-local variables can also be non-volatile, like in Java for instance.

GO has the concept of channel, which, by it’s nature – inter thread communication, means it bypasses processor cache, and reads/writes to heap directly.

Also, have not found any reference to volatile in the go lang documentation.

1 Like

TL;DR : Go does not have a keyword to make a variable safe for multiple goroutines to write/read it. Use the sync/atomic package for that. Or better yet Do not communicate by sharing memory; instead, share memory by communicating.

Two answers for the two meanings of volatile

.NET/Java concurrency

Some excerpts from the Go Memory Model.

If the effects of a goroutine must be observed by another goroutine, use a synchronization mechanism such as a lock or channel communication to establish a relative ordering.

One of the examples from the Incorrect Synchronization section is an example of busy waiting on value.

Worse, there is no guarantee that the write to done will ever be observed by main, since there are no synchronization events between the two threads. The loop in main is not guaranteed to finish.

Indeed, this code( never exits.

C/C++ non-standard memory

Go’s memory model does not provide a way to address non-standard memory. If you have raw access to a device’s I/O bus you’ll need to use assembly or C to safely write values to the memory locations. I have only ever needed to do this in a device driver which generally precludes use of Go.

Refer: stackoverflow