Skip to content

Instantly share code, notes, and snippets.

@wuriyanto48
Created June 16, 2017 13:25
Show Gist options
  • Save wuriyanto48/9f21dc1cf868be0b6f5bfd6d0609f9a0 to your computer and use it in GitHub Desktop.
Save wuriyanto48/9f21dc1cf868be0b6f5bfd6d0609f9a0 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"sync"
)
var wg sync.WaitGroup
type Processor struct {
mu sync.Mutex
sum int
}
func (p *Processor) process(n string) {
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < 10000; i++ {
p.mu.Lock()
p.sum = p.sum + 1
p.mu.Unlock()
}
fmt.Println("From " + n + ":", p.sum)
}()
}
func main() {
processes := []string{"A", "B", "C", "D", "E"}
processor := &Processor{mu: sync.Mutex{}, sum: 0}
for _, p := range processes {
processor.process(p)
}
wg.Wait()
fmt.Println("Final Sum:", processor.sum)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment