In Go, you can manage deadlines and timeouts using the `context` package, which allows you to pass a context through your application to control cancellation signals and deadlines.
Context is useful for managing timeouts in functions, making it easy to handle long-running tasks. Here’s an example of how to set a deadline and timeout using context:
package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
go func() {
// Simulating a long-running task
time.Sleep(3 * time.Second)
fmt.Println("Task finished")
cancel() // Cancel the context when the task finishes
}()
select {
case <-ctx.Done():
// Handle the case when the context is done (either timeout or manually canceled)
fmt.Println("Operation timed out:", ctx.Err())
}
fmt.Println("Finished execution")
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?