Skip to content

Instantly share code, notes, and snippets.

@gfonseca
Last active October 20, 2017 21:09
Show Gist options
  • Save gfonseca/682ceaeab23f67864c32c93ac7981bf4 to your computer and use it in GitHub Desktop.
Save gfonseca/682ceaeab23f67864c32c93ac7981bf4 to your computer and use it in GitHub Desktop.
This simple program writen in Golang show how to transfer messages by go chanels, and how to sync the goroutines output
package main
/*
This simple program show how to transfer messages by go chanels,
and how to sync the goroutines output
*/
import (
"fmt"
"math/rand"
"sync"
"time"
)
const workersn int = 50
func main() {
c := make(chan string)
var wg sync.WaitGroup
// Adding 50 wait locks to WaitGroup
wg.Add(workersn)
// Start 50 goroutines
for i := 0; i < workersn; i++ {
// anonymous function for printing a common message
go func(i int) {
// This remove a wait lock
defer wg.Done()
d := rand.Intn(5000)
time.Sleep(time.Duration(d) * time.Millisecond)
// Printing a common message
c <- fmt.Sprintf("Go routine %d done.", i)
}(i)
}
// this goroutine print the content of the others
go func(c chan string) {
for j := 0; j < workersn; j++ {
// Receive the message from other goroutines by chanel
fmt.Println(<-c)
}
}(c)
// Put it in idle until all goroutines are done
// When all the locks was removed the program go ahead
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment