Welcome To Golang By Example

Pause Execution of a goroutine until an activity or event is completed in Go (Golang)

Table of Contents

Overview

Channels can be used to pause the execution of a goroutine until an activity is completed. For a

Unbuffered Channel

Buffered Channel

If we want a goroutine to pause until an activity is complete, we can use any of the above four ways. For simplicity in this tutorial, we are going to use an unbuffered channel. The goroutine will do a receive operation on that channel and it will pause. It will only resume if a send operation is done on that channel in a different goroutine. 

Program

package main

import (
	"fmt"
	"time"
)

func main() {
	ch := make(chan bool)
	go test(ch)

	time.Sleep(time.Second * 1)
	fmt.Printf("Send Value: %t\n", true)
	ch <- true

	time.Sleep((time.Second * 3))
}

func test(ch chan bool) {
	var value = <-ch
	fmt.Printf("Received Value: %t\n", value)
	fmt.Println("Doing some work")
}

Output

Send Value: true
Received Value: true

In the above program, we create an unbuffered channel.  We start a goroutine which waits for a receive operation on that channel. It will be blocked until a send operation is done.

We then send the value in the main goroutine. Once the send is complete, then the goroutine resumes execution. That is why

Send Value: true

is always printed before

Send Value: true
Received Value: true

Also, check out our Golang comprehensive tutorial Series - Golang Comprehensive Tutorial