July 2019
Intermediate to advanced
458 pages
12h 12m
English
This function can be very helpful for defining thread-safe components really easily. A very obvious example could be a simple integer counter that uses Add to change the counter, Load to retrieve the current value, and Store to reset it:
type clicker int32func (c *clicker) Click() int32 { return atomic.AddInt32((*int32)(c), 1)}func (c *clicker) Reset() { atomic.StoreInt32((*int32)(c), 0)}func (c *clicker) Value() int32 { return atomic.LoadInt32((*int32)(c))}
We can see it in action in a simple program, which tries to read, write, and reset the counter concurrently.
We define the clicker and WaitGroup and add the correct number of elements to the wait group as follows:
c := clicker(0)wg := sync.WaitGroup{}// 2*iteration + reset ...Read now
Unlock full access