Junhee Woo
Junhee Woo

Reputation: 93

Why atomic.Value must not be copied after the first Store?

A Value provides an atomic load and store of a consistently typed value. The zero value for a Value returns nil from Load. Once Store has been called, a Value must not be copied.

I read the above comment from atomic.Value. It says that "a Value must not be copied", but the reason is not stated.

Why atomic.Value must not be copied after the first Store?

Upvotes: 2

Views: 1107

Answers (2)

kostix
kostix

Reputation: 55533

In addition to the answer by @Volker and the comment by @icza, the reasoning is quite simple: the implementation of atomic.Value includes something which is used to provide the atomicity guaranteed by the type's contract, directly — as opposed to including a reference to or, as it usually happens, a pointer to, such thing, and hence when a variable of type atomic.Value is copied to another variable that "thing" is copied, (cloned) too.

Now suppose that an implementation decided to include into the type of atomic.Value a (usually kernel-provided) semaphore or mutex, or critical section or whatever else — any convenient locking mechanism.

Consider now a case of contention: some goroutine tries to read the value while another one tries to modify it, in parallel. The writing goroutine "acquires" "exclusive write permission" via that internal protection mechanism — however it is implemented — and then you copy the value. Leaving aside the problem of such copying creating a classical data race case, you can now see that the result of the copy will be two variables of type atomic.Value, and each of them will be "locked" for that exclusive write permission. But while the original variable remains in a sensible state — the goroutine which wanted to update the variable will eventually be done with that and will "release" its permit back, returning the variable into the normal state, the copy will be forever latched in that "acquired for update" state while there is no goroutine intending to perform that update. Oops!


By the way, you cannot copy sync.Mutex variable after its first use for precisely the same reasons.

Upvotes: 3

Volker
Volker

Reputation: 42431

Why atomic.Value must not be copied after the first Store?

Because the documentation says so.

(The internal implementation requires this. Nothing to see here, there is no actionable thing about this.)

Upvotes: 0

Related Questions