talks

git clone git://code.dwrz.net/talks
Log | Files | Refs

main.go (791B)


      1 package main
      2 
      3 import (
      4 	"fmt"
      5 	"sync"
      6 )
      7 
      8 func main() {
      9 	var balance int = 100
     10 	// var mu sync.Mutex
     11 
     12 	fmt.Println("Initial balance:", balance)
     13 
     14 	// Apply concurrent adjustments to the balance.
     15 	// The sum of these adjustments is 0.
     16 	// We should see no changes in balance at the end.
     17 	var adjustments = []int{
     18 		-8, -4, -2, 0, 2, 4, 8,
     19 		-8, -4, -2, 0, 2, 4, 8,
     20 		-8, -4, -2, 0, 2, 4, 8,
     21 		-8, -4, -2, 0, 2, 4, 8,
     22 		-8, -4, -2, 0, 2, 4, 8,
     23 		-8, -4, -2, 0, 2, 4, 8,
     24 	}
     25 
     26 	var wg sync.WaitGroup
     27 	wg.Add(len(adjustments))
     28 
     29 	for _, adjustment := range adjustments {
     30 		// go = placed onto thread, not the stack.
     31 		go func(adjustment int) {
     32 			defer wg.Done()
     33 
     34 			// mu.Lock()
     35 
     36 			balance += adjustment
     37 
     38 			// mu.Unlock()
     39 
     40 		}(adjustment)
     41 	}
     42 
     43 	wg.Wait()
     44 
     45 	fmt.Println("Final balance:", balance)
     46 }