Skip to content

Instantly share code, notes, and snippets.

@Jalalx
Last active August 14, 2021 18:53
Show Gist options
  • Save Jalalx/d53ad7de5b4db1c5df49a27690437e30 to your computer and use it in GitHub Desktop.
Save Jalalx/d53ad7de5b4db1c5df49a27690437e30 to your computer and use it in GitHub Desktop.
Basic producer-consumer app using channels in golang

Create a file named app.go and paste following code in it:

package main

import (
	"fmt"
	"strconv"
	"time"
)

func main() {
	work := make(chan string)
	go producer(work)
	go consumer(work)

	fmt.Scanln()
}

func producer(work chan string) {
	index := 1
	for {
		work <- "work " + strconv.Itoa(index)
		time.Sleep(time.Millisecond * 500)
		index++
	}
}

func consumer(work chan string) {
	for w := range work {
		fmt.Println(w)
	}
}

And then run it:

go run app.go

Here is the same process with a middle modifier:

package main

import (
	"fmt"
	"strconv"
	"time"
)

func main() {

	work := make(chan string)

	go producer(work)
	go modifier(work)
	go consumer(work)

	fmt.Scanln()
}

func producer(work chan string) {
	index := 1
	for {
		work <- "work " + strconv.Itoa(index)
		time.Sleep(time.Millisecond * 500)
		index++
	}
}

func modifier(work chan string) {
	for w := range work {
		t := w + " modified"
		work <- t
	}
}

func consumer(work chan string) {
	for w := range work {
		fmt.Println(w)
	}
}

And here is the third one. The modifier reads from one channel and writes to another:

package main

import (
	"fmt"
	"strconv"
	"time"
)

func main() {

	input := make(chan string)
	output := make(chan string)

	go producer(input)
	go modifier(input, output)
	go consumer(output)

	fmt.Scanln()
}

func producer(input chan string) {
	index := 1
	for {
		input <- "work " + strconv.Itoa(index)
		time.Sleep(time.Millisecond * 500)
		index++
	}
}

func modifier(input chan string, output chan string) {
	for w := range input {
		t := w + " modified"
		output <- t
	}
}

func consumer(output chan string) {
	for w := range output {
		fmt.Println(w)
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment