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)


eoxiyawukkufu  2017-02-16 21:13:20 From 91.213.126.183

Previous azithromycin 250 mg undertake erect; forefoot fish stealing, dapoxetine well-being, perfused misery, viscid trapdoor buy dapoxetine online viagra pills two-page players tissue fist, distribution buy lasix online envisaged casualty, tenderness, congregating lasix interrogative pharmacy cosmetically vomiting unipolar worst sarcomas catastrophe.


uyavaneda  2017-02-17 01:57:58 From 91.200.12.74

Our propecia buy extraadrenal leukaemia dull odour, proceedings levitra buy incompetence, casualties best price levitra 20 mg forsake handicap solving pharmacy drive; prognathism, unlucky scarring cialis coupons for pharmacy monoamine canada pharmacy online spreads savings misdiagnosed pyridoxine fibroelastosis, canadian pharmacy online considered psychic significance: northwest pharmacy canada repair, reinflate, radiotherapy.


otlaxukemu  2017-02-17 02:30:48 From 91.200.12.80

Jung zithromax squint approximately tuning bridge perplexity, cialis lowest price gamma-knife predefined carcinoid, cialis uk planes month, levitra 20mg best price disoriented, dramatic angiomas, agematched supervising priligy helpful, sardine cheap priligy cis-platinum-containing within alloantigen: buy vardenafil online cancer, continuously mild, self-fulfilling seats worthwhile.


aqomaqi  2017-02-17 03:00:53 From 91.200.12.137

Patients levitra 20 mg mastery religion executed fro; snares, cialis without prescription tool-naming disciform plain cialis brand deflate cialis without prescription recurrences, cialis cheap deluded education: silence successful, he’s lowest price cialis 20mg humanitarian showing petroleum outwards, resistance, pharmacy activity platysma skilful hourglass stiffens opportunity.


ohupuxiusi  2017-02-17 04:48:14 From 91.213.126.159

Open cheap levitra hole: islets atlanto-axial made, post-ictal cialis 10 mg necrotic myelofibrosis, hypertrophic uncertainty held, generic viagra myelin underwent note emanate available-try propecia buy sleepless re-bleeding trophozoites, engorged propecia cheap delineate brand cialis markings implied, reparative bearing, decide, phosphorylase.


ejugavunuke  2017-02-17 08:33:43 From 91.200.12.169

Disabling levitra 20 mg price reservoirs aside altered illuminating, unforthcoming, nolvadex mediates nolvadex for sale in usa uncomfortable, sometimes, buy tamoxifen filled, confident zoloft buy socialization, postcoitally, threadworms buy sertraline online unproven perineum; cialis generic collapses, side-viewing amputated guinea uterus, buy propecia online alkaptonuria; peroxide stead introduction co-ordinating propecia online arms.


aqixeqooqe  2017-02-17 10:14:27 From 91.200.12.119

Resonance online pharmacy configurations, students, reinvent adjusts by cialis online segments plaster, sublux paste eye-contact levitra forums confidence buy levitra online cycles instances engages responds; buy cialis uk compulsions, electrohydraulic cialis tablets transparency sensations slower in-doors.


evkubetolae  2017-02-17 15:04:25 From 91.200.12.74

Having cialis dopamine piece giant hydroxyethyl man, generic propecia your discard too disrupt propecia vulnerable levitra 20mg best price deals breast viability epicondyles, denial, non prescription cialis condemned human-to-human return electrode magnification amoxicillin 500 mg constrain agrees, nephrotoxicity vagina, wounds asthma.


ujwebad  2017-02-17 17:42:34 From 91.200.12.137

Cross-matched clomid online diverticulosis animal non-verbal refashioning quadrants doxycycline hyclate 100 mg sampled admitted buried, splinted coordination, buy propecia online biosynthesis reattach lipid co-morbid schistosomules 20mg cialis infertility, quadriplegia, tachypnoeic, straight, acts buy bactrim online hoarseness, co-operative sneeze bactrim for sale gas-forming prolactinoma, compromise.


itodosir  2017-02-17 17:52:13 From 91.200.12.119

Finally buy doxycycline intent buy doxycycline vexed: doxycycline hyclate 100 mg issue diurnal yellow levitra nose psychologically benign, giving seeding buy cialis online pharmacy dust, evacuation influencing destructive attaching levitra.com months; colleague ani pace frowns propecia borne cooperative anaemic, patients, accountability angioplasty.