What you are doing is what sync.Once was invented for: https://play.golang.org/p/erZqwFYgIR
On Tue, Oct 17, 2017 at 11:37 PM, Juliusz Chroboczek <j...@irif.fr> wrote: > > The answer depends on whether you have just one value or many. For a > single > > value (sometimes known as a "future"), I tend to pair a chan of struct{} > > with a value to be set. To make the value available, set it, then close > the > > channel. Readers wait on the channel, then read the value. > > That's an interesting idea. Surprisingly enough, it turns out to be > only slightly slower than the obvious implementation with a mutex, and > (even more suprisignly) actually faster when using hardware threading. > This is on a 2-core hyperthreaded SandyBridge (4 hardware threads): > > BenchmarkMutexFuture 100000000 22.2 ns/op > BenchmarkMutexFuture-2 50000000 39.9 ns/op > BenchmarkMutexFuture-4 20000000 86.0 ns/op > BenchmarkAtomicFuture 200000000 7.01 ns/op > BenchmarkAtomicFuture-2 500000000 3.69 ns/op > BenchmarkAtomicFuture-4 1000000000 2.69 ns/op > BenchmarkChannelFuture 50000000 29.7 ns/op > BenchmarkChannelFuture-2 50000000 54.6 ns/op > BenchmarkChannelFuture-4 20000000 64.4 ns/op > > Code here: https://play.golang.org/p/Wm71o50HJ8 > > -- Juliusz > > -- > You received this message because you are subscribed to the Google Groups > "golang-nuts" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to golang-nuts+unsubscr...@googlegroups.com. > For more options, visit https://groups.google.com/d/optout. > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.