登录
首页 >  Golang >  Go问答

在单独的 go 例程中重置计时器

来源:Golang技术栈

时间:2023-04-23 19:28:56 106浏览 收藏

大家好,我们又见面了啊~本文《在单独的 go 例程中重置计时器》的内容中将会涉及到golang等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~

问题内容

TimeOutTime在以下场景中,网络实体在执行特定任务之前总是等待几秒钟X。假设这个时间为TimerTTimeOutTime如果实体收到一组外部消息,则在此等待几秒钟期间,它应该再次将其重置TimerTTimeOutTime。如果没有收到外部消息,则预期行为如下:

  1. 计时器已过期
  2. 执行任务 X
  3. 再次将计时器重置为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()
            

-race使用标志运行此程序后,它显示DATA_RACE

==================
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()
            

根据以下观察,此代码似乎可以正常工作。

如果我更换线路

time.Sleep(time.Second * time.Duration(rand.Intn(MeanArrivalTime)))

在第二个 go 例程中,睡眠时间为 ,4 seconds并且TimeOutTime3 seconds

程序的输出是:

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() {
//      

我找到了这张图:(链接:[https](https://blogtitle.github.io/go-advanced-concurrency- patterns-part-2-timers/) ://blogtitle.github.io/go-advanced-concurrency- patterns-part-2-timers/ )

时间图 GoLang

考虑到图表,我似乎需要使用,

if !t.Stop() {
    

2ndgo 例程中。在这种情况下,我还需要在两个 go 例程中进行适当的锁定,以避免在通道上无限等待。

我不明白t.Stop() + draining of the channel (应该在什么情况下执行。在什么情况下需要?在我的示例中,我不使用通道读取值。我可以在不调用 Stop() 的情况下调用 Reset() 吗?

正确答案

time.After我使用函数简化了代码:

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 

注意:

After等待持续时间过去,然后在返回的通道上发送当前时间。它相当于NewTimer(d).C。在定时器触发之前,垃圾收集器不会恢复底层定时器。如果效率是一个问题,请改用并在不再需要计时器时NewTimer 调用。Timer.Stop

以上就是《在单独的 go 例程中重置计时器》的详细内容,更多关于golang的资料请关注golang学习网公众号!

声明:本文转载于:Golang技术栈 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>