Mutex example

1.Without

package main
import "fmt"

var counter int = 0             
func main() {

    ch := make(chan bool)        
    for i := 1; i < 5; i++{
        go work(i, ch)
    }

    for i := 1; i < 5; i++{
        <-ch
    }
    fmt.Println("The End")
}
func work (number int, ch chan bool){
    counter = 0
    for k := 1; k <= 5; k++{
        counter++
        fmt.Println("Goroutine", number, "-", counter)
    }
    ch <- true
}

Output

Goroutine 3 - 1
Goroutine 3 - 2
Goroutine 3 - 3
Goroutine 3 - 4
Goroutine 3 - 5
Goroutine 2 - 1
Goroutine 2 - 6
Goroutine 2 - 7
Goroutine 2 - 8
Goroutine 2 - 9
Goroutine 1 - 1
Goroutine 1 - 10
Goroutine 1 - 11
Goroutine 1 - 12
Goroutine 1 - 13
Goroutine 4 - 1
Goroutine 4 - 14
Goroutine 4 - 15
Goroutine 4 - 16
Goroutine 4 - 17
The End

2. With

package main
import (
"fmt"
"sync"
)

var counter int = 0           
func main() {

    ch := make(chan bool)     
    var mutex sync.Mutex      
    for i := 1; i < 5; i++{
        go work(i, ch, &mutex)
    }

    for i := 1; i < 5; i++{
        <-ch
    }

    fmt.Println("The End")
}
func work (number int, ch chan bool, mutex *sync.Mutex){
    mutex.Lock()   
    counter = 0
    for k := 1; k <= 5; k++{
        counter++
        fmt.Println("Goroutine", number, "-", counter)
    }
    mutex.Unlock() 
    ch <- true
}

Output

Goroutine 1 - 1
Goroutine 1 - 2
Goroutine 1 - 3
Goroutine 1 - 4
Goroutine 1 - 5
Goroutine 4 - 1
Goroutine 4 - 2
Goroutine 4 - 3
Goroutine 4 - 4
Goroutine 4 - 5
Goroutine 3 - 1
Goroutine 3 - 2
Goroutine 3 - 3
Goroutine 3 - 4
Goroutine 3 - 5
Goroutine 2 - 1
Goroutine 2 - 2
Goroutine 2 - 3
Goroutine 2 - 4
Goroutine 2 - 5
The End

@blog

golang