This is the twelfth entry of my weekly series Learning Go. Last week I talked about using Goroutines and WaitGroups to make use of concurrent patterns in Go. This week I will continue to expand on the topic of concurrency by showing you how to use a few more useful features of Go: Channels and Mutex. I will also walk you through how you can identify and fix potential race conditions in your code. Let’s get to it!

Channels

a “pipe” that allows you to send and receive values in your concurrent Goroutines

Essentially, Channels can be thought of as messengers that you can send to various Goroutines to deliver or retrieve values

  • Channels block
  • They are synchronized
  • They have to pass or receive the value at the same time

Channels have two important pieces of syntax <- and ->

When you want to send data onto a Channel you use this syntax channel <-

When you want to retrieve data from a Channel you use this syntax <- channel

Let me show you a quick example to see Channels in action

package main

	import (
		"fmt"
	)

	func main() {
		c := make(chan int)

		go func() {
			c <- 29
		}()

		fmt.Println(<-c)
	}

#beginner #golang #tutorial #programming #google

Concurrency in Go — Using Channels, Mutex, and Handling Race Conditions
1.35 GEEK