在单独的 go 例程中重置计时器
来源:Golang技术栈
时间:2023-04-23 19:28:56 106浏览 收藏
大家好,我们又见面了啊~本文《在单独的 go 例程中重置计时器》的内容中将会涉及到golang等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~
问题内容
TimeOutTime在以下场景中,网络实体在执行特定任务之前总是等待几秒钟X。假设这个时间为TimerT。TimeOutTime如果实体收到一组外部消息,则在此等待几秒钟期间,它应该再次将其重置TimerT为TimeOutTime。如果没有收到外部消息,则预期行为如下:
- 计时器已过期
- 执行任务 X
- 再次将计时器重置为
TimeOutTime
(reset我的意思是,停止计时器并重新开始)

为了模拟场景,我在 Go 中编写了以下代码。
package main
import (
"log"
"math/rand"
"sync"
"time"
)
const TimeOutTime = 3
const MeanArrivalTime = 4
func main() {
rand.Seed(time.Now().UTC().UnixNano())
var wg sync.WaitGroup
t := time.NewTimer(time.Second * time.Duration(TimeOutTime))
wg.Add(1)
// go routine for doing timeout event
go func() {
defer wg.Done()
for {
t1 := time.Now()
<p><code>-race</code>使用标志运行此程序后,它显示<code>DATA_RACE</code>:</p>
<pre class="brush:go;toolbar:false">==================
WARNING: DATA RACE
Write at 0x00c0000c2068 by goroutine 8:
time.(*Timer).Reset()
/usr/local/go/src/time/sleep.go:125 +0x98
main.main.func1()
/home/deka/Academic/go/src/main/test.go:29 +0x18f
Previous write at 0x00c0000c2068 by goroutine 9:
time.(*Timer).Reset()
/usr/local/go/src/time/sleep.go:125 +0x98
main.main.func2()
/home/deka/Academic/go/src/main/test.go:42 +0x80
Goroutine 8 (running) created at:
main.main()
/home/deka/Academic/go/src/main/test.go:20 +0x1d3
Goroutine 9 (running) created at:
main.main()
/home/deka/Academic/go/src/main/test.go:35 +0x1f5
==================
然后我使用 Mutex 将Reset()调用包装在 Mutex 中。
包主
import (
"log"
"math/rand"
"sync"
"time"
)
const TimeOutTime = 3
const MeanArrivalTime = 4
func main() {
rand.Seed(time.Now().UTC().UnixNano())
var wg sync.WaitGroup
t := time.NewTimer(time.Second * time.Duration(TimeOutTime))
wg.Add(1)
var mu sync.Mutex
// go routine for doing timeout event
go func() {
defer wg.Done()
for {
t1 := time.Now()
<p>根据以下观察,此代码似乎可以正常工作。</p>
<p>如果我更换线路</p>
<p><code>time.Sleep(time.Second * time.Duration(rand.Intn(MeanArrivalTime)))</code></p>
<p>在第二个 go 例程中,睡眠时间为 ,<code>4 seconds</code>并且<code>TimeOutTime</code>为<code>3 seconds</code>。</p>
<p>程序的输出是:</p>
<pre class="brush:go;toolbar:false">2020/02/29 20:10:11 Timeout after 3.000160828s
2020/02/29 20:10:15 Timeout after 4.000444017s
2020/02/29 20:10:19 Timeout after 4.000454657s
2020/02/29 20:10:23 Timeout after 4.000304877s
在上面的执行中,2ndgo 例程active timer在计时器花费初始一秒后重置。因此,从第二次打印开始的几秒钟timer后,它就会过期。4
现在,当我检查文档时,Reset()我发现以下内容:
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Reset changes the timer to expire after duration d.
// It returns true if the timer had been active, false if the timer had
// expired or been stopped.
//
// Reset should be invoked only on stopped or expired timers with drained channels.
// If a program has already received a value from t.C, the timer is known
// to have expired and the channel drained, so t.Reset can be used directly.
// If a program has not yet received a value from t.C, however,
// the timer must be stopped and鈥攊f Stop reports that the timer expired
// before being stopped鈥攖he channel explicitly drained:
//
// if !t.Stop() {
//
<p>我找到了这张图:(链接:[https](https://blogtitle.github.io/go-advanced-concurrency-
patterns-part-2-timers/) ://blogtitle.github.io/go-advanced-concurrency-
patterns-part-2-timers/ )</p>
<p><img src="./page_107_21_files/owEnr.png" alt="时间图 GoLang"></p>
<p>考虑到图表,我似乎需要使用,</p>
<pre class="brush:go;toolbar:false">if !t.Stop() {
<p>在<code>2nd</code>go 例程中。在这种情况下,我还需要在两个 go 例程中进行适当的锁定,以避免在通道上无限等待。</p>
<p>我不明白<code>t.Stop() + draining of the channel (应该在什么情况下执行。在什么情况下需要?在我的示例中,我不使用通道读取值。我可以在不调用 Stop() 的情况下调用 Reset() 吗?</code></p>
<h2 class="daan">
正确答案
</h2>
<p><code>time.After</code>我使用函数简化了代码:</p>
<pre class="brush:go;toolbar:false">package main
import (
"log"
"math/rand"
"time"
)
const TimeOutTime = 3
const MeanArrivalTime = 4
func main() {
const interval = time.Second * TimeOutTime
// channel for incoming messages
var incomeCh = make(chan struct{})
go func() {
for {
// On each iteration new timer is created
select {
case
<p>注意:</p>
<blockquote>
<p><code>After</code>等待持续时间过去,然后在返回的通道上发送当前时间。它相当于<code>NewTimer(d).C</code>。在定时器触发之前,垃圾收集器不会恢复底层定时器。如果效率是一个问题,请改用并在不再需要计时器时<code>NewTimer</code>
调用。<code>Timer.Stop</code></p>
</blockquote><p>以上就是《在单独的 go 例程中重置计时器》的详细内容,更多关于golang的资料请关注golang学习网公众号!</p>
声明:本文转载于:Golang技术栈 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
-
439 收藏
-
262 收藏
-
193 收藏
-
188 收藏
-
500 收藏
最新阅读
更多>
-
139 收藏
-
204 收藏
-
325 收藏
-
478 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
课程推荐
更多>
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习