Created
October 31, 2021 04:54
-
-
Save pkbhowmick/29f9966b08a3b1781586ffe7ec5e653b to your computer and use it in GitHub Desktop.
An example of buffered channel in Golang
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
// In Go, there are mainly two types of channel. | |
// 1. Unbuffered channel | |
// 2. Buffered channel | |
// Buffered channel can work asyncronously | |
// Let's see an example of buffered channel | |
package main | |
import ( | |
"fmt" | |
"sync" | |
) | |
var msgs []string = []string{"msg1", "msg2", "msg3", "msg4", "msg5"} | |
var wg sync.WaitGroup | |
func SendMessage(ch chan string,msg string) { | |
fmt.Println("Sending msg: ", msg) | |
ch <- msg | |
wg.Done() | |
} | |
func main() { | |
len := len(msgs) | |
wg.Add(len) | |
bufferedChan := make(chan string, len) | |
defer close(bufferedChan) | |
for _,msg := range msgs { | |
go SendMessage(bufferedChan, msg) | |
} | |
wg.Wait() | |
for i:=0;i<len;i++ { | |
receivedMsg := <- bufferedChan | |
fmt.Println("Received msg: ", receivedMsg) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment