Last active
October 20, 2017 21:09
-
-
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
This file contains hidden or 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 | |
/* | |
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