DEV Community

urgensherpa
urgensherpa

Posted on

Context

#go

Context allow you to send cancellation signal to asynchronous process/ go-routine.
context

Methods provided by context interface:-

Value(key) This method returns the value associated with the specified key.

**Done() **This method returns a channel that can be used to receive a cancelation notification.

Deadline() This method returns the Time that represents the deadline for the request and a bool value that will be false if no deadline has been specified.

Err() This method returns an error that indicates why the Done channel received a signal. The context package defines two variables that can be used to compare the error: Canceled indicates that the request was canceled, and DeadlineExeeded indicates that the deadline passed.

Functions https://pkg.go.dev/context#pkg-functions

  • Background()
  • WithCancel(ctx)
  • WithDeadline(ctx,time)
  • WithTimeout(ctx,duration)
  • WithValue(ctx, key,val)
package main

import (
    "sync"
    "time"
    "fmt"
    "context"
)

func processRequest(ctx context.Context, wg *sync.WaitGroup, count int) {
    total := 0
    for i := 0; i < count; i++ {
        select {
        case <-ctx.Done():
            fmt.Println("Stopping processing - request cancelled")
            goto end
        default:
            fmt.Printf("Processing request: %v \n", total)
            total++
            time.Sleep(time.Millisecond * 250)
        }
    }
    fmt.Println("%v Request processed...", total)
end:
    wg.Done()
}
func main() {
    waitGroup := sync.WaitGroup{}
    waitGroup.Add(1)
    fmt.Println("Request dispatched...")
    ctx, cancel := context.WithCancel(context.Background())

    go processRequest(ctx, &waitGroup, 10)
    time.Sleep(time.Second)
    fmt.Println("Canceling req")
        cancel()
    waitGroup.Wait()

}

---

% go run contxt.go
Request dispatched...
Processing request: 0 
Processing request: 1 
Processing request: 2 
Processing request: 3 
Canceling request
Stopping processing - request cancelled
Enter fullscreen mode Exit fullscreen mode

Top comments (0)