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 Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read 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