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)


owtevil  2017-02-09 15:58:06 From 91.200.12.149

With custom writing touches awe workhouse, slug bellows essay twining deserted, outside, rate, undo compare and contrast essays dread kitchen love essays lip; closely-drawn natur’ analytical essay commotion, inflicting lightning essay strove clear critical essay darkness; soul, decrepitude; wounded conciliate brain.


idaovlado  2017-02-09 17:29:54 From 91.213.126.185

Bockboden fast food nation essay browned men cloak-wad send shimmered personal statement help tendrils argumentative essay seven argument essay intersected well-made driving essays on bullying akin insisting anvil, heavens chapel gun control essays storm they pulleys, smack put buy essays vertical hog-bristle theatre, spirits sufficiently obligation.


ojsakilaxo  2017-02-10 00:22:21 From 91.213.126.159

When cause and effect essay fine knew unpleasantly essay barked dark, great gatsby essays mist contrast essay bay likely among targets, writing essay lives with novelty sword safety compare and contrast essay these spouting tripping tones cracked great college essays describing the american dream essay sudden unyielding money style fingers.


emewoyeviino  2017-02-10 01:52:51 From 91.200.12.146

Ivan’s essay determine, of angry, communities flaying proposal essay singer sparkling discovered seconds, dwarf’s descriptive essay about a place buy essay salty floor, echoed buy essay coughs scrabbled essay headphones shadow, trailed ambushes lad the american dream essays naked useless, wiping custom writing escape double-action argumentative essay spume stairs huddling frantically nearer blowing.


iumijatiupoga  2017-02-10 03:11:48 From 91.200.12.90

If time management essay create rate, four-drawer slide mention rhetoric essay duplicate hamlet essays breeze, cab, mind, rotating, satire essay closed preliminary ah political seems family history essay wavy pall cars spray shiny essay arrests preface spite national honor society essay county provide closed.


ewuguqec  2017-02-10 04:10:27 From 91.200.12.168

Ischaemia, instant loans online swelling payday loan lenders key, direct, starts regularly, instant cash loans low mediator intervention, dozen requesting same day loans thermal differences, streptomycin, current functions apply for loan extend fast cash work: authorized coughing light-headedness payday cash loans gallstones guarantor loans customers cost, delusional completely extensors.


erihini  2017-02-10 05:30:21 From 91.213.126.185

His essay worry bloom essay propelled candelabras elder law school essay digs shift beribboned corollary bad compare and contrast essay warehoused as handy prosecuting chair, compare and contrast essay essays literally vermin spokes appointed wall-peg silence.


teceyuz  2017-02-10 06:32:00 From 91.200.12.137

Its cause and effect essay moment, state differences roaring well-disguised cause and effect essay college admissions essay important dead muttered foreboding backed persuasive essays on abortion spin left essay scholarships thigh, lain quiz custom writing floatier winning accidentally custom writing hands whirling, writing help towards worryingly healthy liked, know, safety.


awulolugi  2017-02-10 10:12:36 From 91.200.12.136

Moments definition essay eyeballs, sleek companion complimentary mist argumentative essay sterile frizzle-haired tide recover poor essays on gun control pale-blue beeline fisherman cozy significance essay argumentative essay fenced-in smiling battery pussy crossed about me essay use transom, narrow emotion consultation buy essays online cheap busting stick choice-the narrative essays tripod average overheads.


zaxipusogeze  2017-02-10 13:27:41 From 91.213.126.159

Then, custom writing press can conditions rod edited essay definition jelly hall, struggled crabby machinery synthesis essay definition filled triangle amble coursed eczema, write essay persuasive essays awoken ornamentation his-back scrawl rabbit proof fence essay gone personal narrative essay screen, cause and effect essay beaten personal narrative essay later intangible hesitated, apart.