Menu Close

WithCancel function in context package in Go

Here, we will are going to learn about WithCancel function in context package in Go with deep understanding and example in details.

The WithCancel function in context package in Go returns a derived context and a cancellation function. The derived context is a copy of the parent context with an additional mechanism to signal cancellation. The cancellation function, when called, cancels the derived context and all its child contexts. This can be useful when you need to propagate a cancellation signal through a chain of function calls or stop a long-running process prematurely.

Syntax:

func WithCancel(parent Context) (ctx Context, cancel CancelFunc)

Example:

Let’s create a simple example to demonstrate the use of the ‘WithCancel’ function. We will create a small Go application that simulates a long-running process and shows how to use the ‘WithCancel’ function to cancel the process.

package main


import (

	"context"

	"fmt"

	"time"

)


func longRunningProcess(ctx context.Context) {

	for {

		select {

		case <-ctx.Done():

			fmt.Println("Process cancelled")

			return

		default:

			fmt.Println("Process running...")

			time.Sleep(1 * time.Second)

		}

	}

}


func main() {

	parentCtx := context.Background()

	ctx, cancel := context.WithCancel(parentCtx)


	go longRunningProcess(ctx)


	time.Sleep(5 * time.Second)

	cancel()


	time.Sleep(2 * time.Second)

	fmt.Println("Main function completed")

}

In this example, the longRunningProcess function simulates a long-running process by repeatedly printing “Process running…” every second. It uses the context’s Done channel to listen for a cancellation signal. If a cancellation signal is received, it prints “Process cancelled” and returns, effectively stopping the process.

In the main function, we create a parent context using context.Background() and then create a derived context and a cancellation function using the ‘WithCancel’ function. We start the long-running process in a separate goroutine, passing the derived context to it. After a sleep duration of 5 seconds, we call the cancellation function to cancel the context, which in turn stops the long-running process. The main function waits for an additional 2 seconds before completing to ensure the long-running process has time to detect the cancellation signal and terminate.

Output:

Process running...
Process running...
Process running...
Process running...
Process cancelled
Main function completed

To learn more about golang, Please refer given below link.

https://www.techieindoor.com/context-package-in-go/

References:

https://golang.org/doc/

Posted in context, golang, packages

Leave a Reply

Your email address will not be published. Required fields are marked *