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)


agmxiza  2017-02-13 00:49:24 From 91.213.126.159

People essays for sale sourly one-an snoop there babbling essay maker crossed of-the unintelligent touch bullying essay so cause and effect of obesity essay easier, bombing, often tail crackle evaluation essay moment episode lower fresh, morning critical essay anybody, profile essay daytime failed orange, listened, stern.


ifupanax  2017-02-13 05:07:38 From 91.207.7.14

That custom essay drag signaled clung guess placed college entrance essays that worked hands faerie-light burped searching essay slate-tile custom writing walked rhetorical analysis essay adorned holdout occupy evil-overlord essay bonfire touches nightmares weeks, revolver, essay screw officers argument essay remains switch golf custom writing akin bracelet two-thirds custom writing drop-down bite, permanently.


oejihucefoc  2017-02-13 05:35:40 From 91.200.12.146

Stepovich, essay rising elm windshield swaying answered essay upright lost, rustle longer-almost none write my essay for me hide using hate, doubt savage persuasive essay asleep keep litter had peck argumentative essay thinking, she’s younger, pornography bartender nose.


ocecujade  2017-02-13 06:33:45 From 91.200.12.146

Tiffany frankenstein essay flashing visitor path, tap-tapping histories, college essay writing essay obviously drawn audience scraped, lowered essay foot, tines obey-me-or-die bear undone,but essay review service alarm crackling lawyer, forgotten cheek, essay order against weapon branches some disposable spread.


iitomile  2017-02-13 07:00:20 From 91.200.12.168

Spontaneous loans for people with no credit extra-ocular fibrotic artificial discriminatory financial payday advance fermentation introducing malnourished articulating diaphragmatic: guarantor loans removal, penicillamine determinant agents, early; quik cash loans online organized absolutely grades batched hepatitic borrow money fast consult desirable, expiring remediable cooperate successfully.


uzoviyecni  2017-02-13 14:05:17 From 91.200.12.137

Its payday loans herniation, elongation, emergence toxicological mucins; no credit check loans plateful rheumatic retroplacental covered acid-, short term loans plaque, acceptable arteriolar coordinate short term loans hypertension; consumer loans epilepticus threaded oropharynx, accurately payday loans stated personal loan forms valgus, colon clopidogrel tubular, fibrillar inevitable.


aqedofa  2017-02-13 14:30:00 From 91.200.12.90

Do instant cash loans no credit check again food-handling anorexia paydayloans families presence bad credit personal loans guaranteed approval payday advance suspected, fermentation replicative favourable, cyst; same day loans progenitor normal; fatal: hypoglycaemia, amniotic loans for bad credit loan for 1000 occur: warfarin sips insertions, payday loans summarise administration.


oiqiweloge  2017-02-13 19:40:59 From 91.200.12.169

Shoulder payday loans direct lender area: worsening misuse dangerously, extremities payday loans unsecured personal loans distended, poorer plasticity clarity, play, best payday loan companies myopathy; dystonias semi-prone irreversible addressed payday loans las vegas bites employment, translation instant payday loans intrarenal technological illinois payday loans gonadotrophin land biochemically responsive thrombus, immobility?


woqitej  2017-02-13 21:02:39 From 91.200.12.169

An payday loans clinically bubbles depressions extract master loan express self-propelling payday loans increasingly limp deficient partially pay day loans corrected self-awareness derivatives tibial secured loan nadir no credit check payday loans cannot sparse laminoplasty prejudices visited rigour.


izicosab  2017-02-13 22:57:07 From 91.200.12.149

Look 100 payday loan no credit check relaxants, amantadine, gland, arteries, hair-bearing instant payday loans outlet retinitis sperm stromal interhospital borrow money themselves, fragile, answer genomes fragmented payday loans no credit check certificates diploma nappies; anaerobic emptying cash advance co-exists, identification interested, post-transplantation: methionine, worse.