Skip to content

Latest commit

 

History

History
43 lines (30 loc) · 821 Bytes

concurrency.timeout.md

File metadata and controls

43 lines (30 loc) · 821 Bytes

Overview

  • Bounded waiting (timeout)

Idioms

  1. Avoid unbounded waiting

Example

func main() {

    timeout := 5 * time.Second

    done := make(chan struct{}, 1)

    go doSlowTask(done)

    // -- Wait for first of ...
    select {
    case <-done:
        // -- wait for task to finish
        fmt.Println("Finished task")

    case <-time.After(timeout):
        // -- wait for timer
        fmt.Println("Timeout")
    }
}

func doSlowTask(done chan<- struct{}) {
    defer func() { done <-struct{} }()

    time.Sleep(3 * time.Second)
}

Other Resources

  1. go by example
  2. golangr
  3. golangbyexample
  4. https://faun.pub/implmenting-timeout-in-golang-ee2bc4aa6ae4