DEV Community

Michele Caci
Michele Caci

Posted on

13 3 1

How to use the context.Done() method in Go to signal goroutine completion

Here is an example of a basic usage of the context package to signal the completion of a task executed in a goroutine:

package main

import (
    "context"
    "log"
    "time"
)

const interval = 500

func main() {
    ctx, cancel := context.WithCancel(context.Background())
    go func() {
        time.Sleep(5 * interval * time.Millisecond)
        cancel()
    }()
    f(ctx)
}

func f(ctx context.Context) {
    ticker := time.NewTicker(interval * time.Millisecond)
    for {
        select {
        case <-ticker.C:
            doSomething()
        case <-ctx.Done():
            return
        }
    }
}

func doSomething() { log.Println("tick") }
Enter fullscreen mode Exit fullscreen mode

Playground link

In this example doSomething() is executed 5 times before the time.Sleep(...) function completes and the cancel function created by the context.WithCancel(...) sends a value to the channel ctx.Done() that will end the for loop and exit.

context.Background() is used as a base for creating a new context variable as described in the context package documentation.

This is a useful way to signal the completion of a task executed in a goroutine and in this context is a powerful alternative to the usage of sync.waitGroup.

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs