Created
June 16, 2017 13:25
-
-
Save wuriyanto48/9f21dc1cf868be0b6f5bfd6d0609f9a0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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