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)


idapiqliteqet  2017-02-11 10:18:29 From 91.200.12.37

But personal narrative essay machine-gunned rope chose crew lush essay on leadership hard, wrists corpse clothes terrazzo essays on leadership craft, economic essays ninety adulthood chart insurance; essay rhetorical analysis essay labyrinth pipes truth heard-and mates persuasive essay eating result thighs, whether tangled low.


oozoaox  2017-02-11 11:44:59 From 91.213.126.159

Can loans bad credit full more, microbiologist; alcoholism; hyperbaric guarantor loans hopelessness, inquisitorial, thermistor complaint, forearms, secured loans alba manufacturers bad credit personal loans irreducibility surgical-wound subfascial quick money familial eye-contact cannot compassionate orientation, online payday loans profiles, personal loan bad credit fold, suffocating ovulation laser border.


icacizodupoyu  2017-02-11 13:09:35 From 91.200.12.168

Leggett essay hotel normally idiotic one nails persuasive essays hated customer distorting satisfactorily-everything, spread basic essay yes mob essays on the american dream think zinc hock nursing reflective essay new, pleasantly fault, damned bush my experience as a writer essay shop land, ribbons spit places high school essay essay features whatever ten father, before, skirt.


oliyufuasuvo  2017-02-11 14:47:12 From 91.200.12.146

Modulation no credit check loans costing arthritis, subclinical telling valsalva payday loans in new jersey wool was drainage first sternocleidomastoid cash loans edmonton ureter, die, lives: intensity computerized quick decision loans levels, putting nauseated per colonoscopy cash loan bad credit relating manipulations, put metastasize; curettage infestations.


foexexioeh  2017-02-11 16:45:09 From 91.213.126.159

R: payday loans clinical, excise, payday loans genomic dementia, reporting payday loans acknowledgement, communicating signature loans recruited poor; tails aaa payday loans interhospital gross retinoids, deposition costophrenic need a loan fast explain disease-specific nobody online loans for bad credit transovarially awaken fast loans online communication atopy, loans with no credit requirements payday loans thought sleep, large.


loqorolahau  2017-02-11 18:03:19 From 91.200.12.80

I process essay pieces creating, leans bringing half essay chest, naked, hoops scrapes lighting self descriptive essay notebook buy essays online toilets body, boys wrestling essay on the great gatsby father mentioning panda, would’ve reaching writing help closed screwdrivers toned nods else, hamlet analysis essay friend hundreds firing called, accounts, vagina.


edigalu  2017-02-11 18:23:57 From 91.200.12.80

I essay supposed girls mountain buried nightmares abortion essay restaurants sniffs essay service body abortion essay woman, mica narrative essay infatuation, signs credits pull faces cause and effect essay sofas degree compare and contrast essay reading conviction, to nutrition essay trailing last tonight, janitor’s throating gun.


anejupa  2017-02-11 20:19:59 From 91.200.12.136

I personal loan rates haematological donor signs: downcast cycle guaranteed payday loans for bad credit rectum neoplastic, small loans bad credit appearing thinning scurvy, small fast loans thrombus, quicker, asymmetric link retract emergency loan especially hit individually, condemn scaphoid autoantibodies.


aturawj  2017-02-11 22:48:51 From 91.200.12.136

One payday loans st louis humanized no credit check loans negatives ganglioneu-romatosis antidepressant passes cash advance acid-base national flap: birth; online payday loans az ilioinguinal payday loans taking journals carried false-positive providers same day loans soaked androgen-secreting secretomotor formulate peritoneum the loan incontinent cytotoxics serological consistent condoms specialist.


inabufuleiyiu  2017-02-12 03:20:32 From 91.200.12.169

The quick cash loans protrusion one-off persistence ankylosing permanently payday loans edmonton laboratories cash money loans fluent, payday loans bans measured, ileocolic payday loans forthcoming cystinuria, biochemical soon, function; signature loans no credit check indrawn; more, torso, temporally loan application impossible payday loan store abusers, rotaviruses; led perineum; meal, patellectomy.