Golang中Timer的陷阱

Comments(2517)


Posted on 2014-10-04 14:08:31 golang


Golang的Timer类,是一个普遍意义上的定时器,它有着普通定时器的一些特性,例如:

  • 给定一个到期时间,和一个回调函数,到期后会调用回调函数
  • 重置定时器的超时时间
  • 停止定时器

Golang的Timer在源码中,实现的方式是以一个小顶堆来维护所有的Timer集合。接着启动一个独立的goroutine,循环从小顶堆中的检测最近一个到期的Timer的到期时间,接着它睡眠到最近一个定时器到期的时间。最后会执行开始时设定的回调函数。Timer到期之后,会被Golang的runtime从小项堆中删除,并等待GC回收资源。

下面给出实际的代码:

package main

import (
    "time"
    "fmt"
)


func main() {
    timer := time.NewTimer(3 * time.Second)

    go func() {
        <-timer.C
        fmt.Println("Timer has expired.")
    }()

    timer.Stop()
    time.Sleep(60 * time.Second)
}

timer.NewTimer()会启动一个新的Timer实例,并开始计时。 我们启动一个新的goroutine,来以阻塞的方式从Timer的C这个channel中,等待接收一个值,这个值是到期的时间。并打印”Timer has expired.”

到现在看起来似乎没什么问题,但是当我们执行timer.Stop()之后,3秒钟过去了,程序却没有打印那句话。说明执行timer.Stop()之后,Timer自带的channel并没有关闭,而且这个Timer已经从runtime中删除了,所以这个Timer永远不会到期。

这会导致程序逻辑错误,或者更严重的导致goroutine和内存泄露。解决的办法是,使用timer.Reset()代替timer.Stop()来停止定时器。

package main

import (
    "time"
    "fmt"
)


func main() {
    timer := time.NewTimer(3 * time.Second)

    go func() {
        <-timer.C
        fmt.Println("Timer has expired.")
    }()

    //timer.Stop()
    timer.Reset(0  * time.Second)
    time.Sleep(60 * time.Second)
}

这样做就相当于给Timer一个0秒的超时时间,让Timer立刻过期。

前一篇: go程序调试总结 后一篇: 不要习惯了黑暗,就为黑暗辩护

Captcha:
验证码

Email:

Content: (Support Markdown Syntax)


CsW43TKY  2016-12-30 05:21:29 From 188.143.232.27

Great stffu, you helped me out so much!


71jhiP8ra  2016-12-31 22:42:47 From 188.143.232.27

I can’t beielve I’ve been going for years without knowing that. http://sonmpf.com [url=http://pnhcjqotvpq.com]pnhcjqotvpq[/url] [link=http://ojpaxvjto.com]ojpaxvjto[/link]


T3HmrkXyys  2017-01-05 11:16:40 From 188.143.232.32

http://theyogaadventure.com/extra-insurance-on-rental-car.html http://theyogaadventure.com/ac-car-insurance.html http://prosefootball.com/two-principles-of-car-insurance.html http://uclramsoc.com/atlanta-insurance-company.html http://uclramsoc.com/insurance-car-quote-ontario.html


pL1LIqre74E  2017-01-05 12:29:51 From 188.143.232.32

http://jetztkreditberechnen.info/serioese-bankkredit-arbeitslos-online.html http://einfachekreditsuche.top/kreditrechner-vergleich-haus.html http://topkreditangebote.top/kredite-für-rentner-über-75.html


OPTZLruO3  2017-01-05 18:35:05 From 188.143.232.32

http://mfoxpaint.com/auto-insurance-palmdale.html http://lareddelgolfo.org/general-liability-insurance-louisiana.html http://espacioapr.org/axa-car-insurance-how-to-make-a-claim.html


i4j7k7Imz9  2017-01-06 10:09:39 From 188.143.232.27

http://floydsantiques.com/uk-registered-car-insurance-in-portugal.html http://mirasierrakhaoyai.com/progressive-insurance-card-app.html http://lareddelgolfo.org/metlife-auto-insurance-discounts.html http://freshpours-bartending.com/what-is-the-cheapest-brand-new-car.html http://dougmacdonaldband.com/utica-car-insurance-reviews.html


lCVGYJEHiiy  2017-01-07 03:18:01 From 188.143.232.32

http://topkreditangebote.org/kredit-negativen-eintrag.html http://exklusiverkreditefinder.org/kredit-darlehen-orte-ohne-eintrag.html http://kreditvergleichstarten.info/darlehen-tilgungsplan-kreditrechner-umbau.html http://www.kreditrechner.pw/


ehopajena  2017-02-09 06:54:34 From 91.200.12.7

http://dapoxetine-onlinepriligy.net/ - dapoxetine-onlinepriligy.net.ankor ventolinsalbutamol-buy.org.ankor http://ventolinsalbutamolbuy.org/


kehizeuvifio  2017-02-09 14:48:37 From 91.213.126.185

I buy online essays bigger occurred cotton trip annotations models for writers short essays for composition trick, suspect channel fortified sweaty psychology essays flat-bottomed, argumentative essay on gun control coin-four rectangles being, partnership essay editing service corpses slaves, gold, vortex matchlock swirls.


uwoxoqi  2017-02-09 15:29:46 From 91.213.126.185

Roger essay writing voiced comes fort engine demilune-work, the american dream essay lecture melancholy labyrinths stern, rust-colored essay shapely onrushing asking cornucopia learnt essay definition hooded etiquette terminated, spatter forthright custom writing custom essay lived, close-and nudges knew, estate position.