golang set timeout
Golang is an efficient programming language that is widely used in development in various fields. In some specific scenarios, we need to set a timeout to avoid deadlock or stuck in the program. In this article, I will introduce in detail how Golang sets timeout, and several ways to set timeout.
1. Use channel
In Golang, you can use channel to implement the timeout function. We can define a channel with a timeout parameter and retrieve the data according to the timeout time after the program is executed.
For example, the following is a simple sample code:
package main import ( "fmt" "time" ) func main() { ch := make(chan string, 1) go func() { time.Sleep(time.Second * 3) ch <- "task completed" }() select { case res := <-ch: fmt.Println(res) case <-time.After(time.Second * 2): fmt.Println("timeout") } }
We can see that a channel with a timeout parameter is created. After the program is executed, a concurrent coroutine will be opened. It takes 3 seconds for the process to perform the task. In the select statement, we listen to two channels. If the data is received within the timeout time, that is, the task execution is completed, the program will print out "task completed". If no data is received within the timeout period, the program will print out "timeout".
2. Using context
In Golang, the context package provides a method for passing request range data, cancellation signals, and timeouts. We can use the WithTimeout function to create a Context object carrying a timeout.
For example, the following is a simple sample code:
package main import ( "context" "fmt" "time" ) func main() { ctx, cancel := context.WithTimeout(context.Background(), time.Second*2) defer cancel() go func(ctx context.Context) { time.Sleep(time.Second * 3) select { case <-ctx.Done(): fmt.Println(ctx.Err()) default: fmt.Println("task completed") } }(ctx) select { case <-ctx.Done(): fmt.Println(ctx.Err()) } }
In this example, we use the WithTimeout function to create a Context object with a timeout of 2 seconds. In the enabled concurrent coroutine, we block and wait for 2 seconds. If the task is completed within 2 seconds, the coroutine will print out "task completed", otherwise it will print out a context timeout error message. In the select statement, we listen to the Done() channel of the Context object. If the Done() channel signal is received, the program will cancel the task and output an error message.
3. Use cancel
In some specific cases, we may need to cancel the execution of a task by setting the cancel function. For example, in a scenario where data is requested from the network, a timeout may be set. If no data is requested within the timeout, we need to cancel the request.
For example, the following is a simple sample code:
package main import ( "context" "fmt" "time" ) func main() { ctx, cancel := context.WithTimeout(context.Background(), time.Second*2) defer cancel() ch := make(chan string, 1) go func(ctx context.Context) { time.Sleep(time.Second * 3) ch <- "task completed" }(ctx) select { case res := <-ch: fmt.Println(res) case <-ctx.Done(): fmt.Println(ctx.Err()) } cancel() }
In this example, we create a Context object carrying a timeout and start a concurrent coroutine to execute the task. In the select statement, we monitor the Done() channel of the task and Context objects. If the task is completed, "task completed" will be output, otherwise a timeout error message will be output. Call the cancel() function at the end of the program to cancel task execution. If the task is completed within the timeout period, the program will exit normally. Otherwise, the program will be blocked in the select statement until the cancel() function is executed.
4. Using deadline
In addition to using the WithTimeout function, the context package also provides another way to time out, that is, using the WithDeadline function. Unlike the WithTimeout function, the parameter of the WithDeadline function is a deadline, not a timeout. When the task is completed before the deadline, the program will exit normally.
For example, the following is a simple sample code:
package main import ( "context" "fmt" "time" ) func main() { ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*2)) defer cancel() go func(ctx context.Context) { time.Sleep(time.Second * 3) select { case <-ctx.Done(): fmt.Println(ctx.Err()) default: fmt.Println("task completed") } }(ctx) select { case <-ctx.Done(): fmt.Println(ctx.Err()) } }
In this example, we use the WithDeadline function to create a Context object with a deadline of 2 seconds. If the task is completed before the deadline, the program will output "task completed", otherwise it will output a timeout error message. In the select statement, we also listen to the Done() channel of the Context object. If a signal from the Done() channel is received, the program will output an error message.
Summary:
Golang provides a variety of ways to set timeouts. By using methods such as channel, context, cancel, and deadline, we can avoid program deadlock or stuck problems and ensure the efficiency and stability of program operation. In actual development, according to different needs and scenarios, we can choose the appropriate method to set the timeout.
The above is the detailed content of golang set timeout. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

This article introduces a variety of methods and tools to monitor PostgreSQL databases under the Debian system, helping you to fully grasp database performance monitoring. 1. Use PostgreSQL to build-in monitoring view PostgreSQL itself provides multiple views for monitoring database activities: pg_stat_activity: displays database activities in real time, including connections, queries, transactions and other information. pg_stat_replication: Monitors replication status, especially suitable for stream replication clusters. pg_stat_database: Provides database statistics, such as database size, transaction commit/rollback times and other key indicators. 2. Use log analysis tool pgBadg

Under the BeegoORM framework, how to specify the database associated with the model? Many Beego projects require multiple databases to be operated simultaneously. When using Beego...

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...
