Learning Concurrency

hi all,

trying to learn concurrency, wondering the use cases of channels and waitgroups

// var wait sync.WaitGroup

type Post struct {
	ID   int
	Text string

func main() {

	var posts []Post

	p1 := CreatePost(1, "yahoo")
	p2 := CreatePost(2, "google 1")
	p3 := CreatePost(3, "excite 2")
	p4 := CreatePost(4, "altavista 3")
	p5 := CreatePost(5, "bing 4")
	posts = append(posts, p1, p2, p3, p4, p5)

    postCh := make(chan Post, 5)
	go GetPosts(postCh, posts)

	for v := range postCh {


func GetPosts(c chan Post, po []Post) {

	for _, v := range po {

		c <- v



func CreatePost(id int, text string) Post {

	return Post{
		ID:   id,
		Text: text,


Channels use case: Pass values between goroutines (rather than sharing memory between goroutines).

Unbuffered channels use case: Provide synchronization between two goroutines. (The sender blocks until the receiver is ready to consume the sent element.)

WaitGroups use case: Spawn a number of goroutines and wait for all of them to complete.

Granted, you can substitute WaitGroups by channels, and channels by mutex-shielded access to shared variables. But channels and wait groups are much easier to read, understand, and reason about.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.