Share & grow the world's code base!

Delve into a community where programmers unite to discover code snippets, exchange skills, and enhance their programming proficiency. With abundant resources and a supportive community, you'll find everything essential for your growth and success.

1 snippets
  • Atomic counters in Go

    package main
    
    import (
    	"fmt"
    	"sync"
    	"sync/atomic"
    )
    
    func main() {
    	var atomicCounter, nonAtomicCounter uint64
    	wg := sync.WaitGroup{}
    
    	for i := 0; i < 50; i++ {
    		wg.Add(1)
    
    		go func() { // run 50 goroutines, each goroutine increases the counter 1000 times
    			for c := 0; c < 1000; c++ {
    				atomic.AddUint64(&atomicCounter, 1) // increase atomic counter
    				nonAtomicCounter++ // increase non-atomic counter
    			}
    
    			wg.Done()
    		}()
    	}
    
    	wg.Wait() // wait until all goroutines finish
    	
    	fmt.Println("atomic counter value:", atomicCounter)
    	fmt.Println("non atomic counter value:", nonAtomicCounter)
    }
    
    // go run counters.go 
    // atomic counter value: 50000
    // non atomic counter value: 30648

    An example of using the sync/atomic package for atomic counters accessed by goroutines.