golang超时等待
妙音
posted @ 2021年5月08日 11:13
in golang
, 797 阅读
描述
go中如何实现超时等待
python实现:队列超时等待
1 | queue.get(block = True , timeout = 45 ) |
go实现:通道+time计时
select会阻塞两个case,直到其中一个返回。如果是response,则停止计时器; 否则,就返回错误
1 2 3 4 5 6 7 8 9 10 11 12 | func _waitResponse(queueChan *chan int, timeout time .Duration) (int, error){ ticker := time .NewTicker(timeout) var response int var err error select { case response = <-*queueChan: ticker.Stop() case <-ticker.C: err = errors.New( "wait response timeout" ) } return response, err } |