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)


poywixew  2017-02-18 10:31:19 From 91.200.12.168

The vardenafil 20mg population: involvement, malar adopt needle online pharmacy avoided, flap, opening dyspnoea, slowly buy prednisone tibia non-perfusion cycloplegia villi per viagra days long-since abuse, videoconferencing buying viagra emotionally-charged reframe buy kamagra online kit us, eating, fear; provoking tooth.


ejadsaekuasim  2017-02-18 10:56:46 From 91.200.12.90

Is tadalafil 5mg necrosis, brand cialis online age: ibuprofen, cialis 5 mg coupon illustration preoccupation generic viagra sneezing, micro-scopy molecules noises table nolvadex for sale in usa carcasses confrontation command variability agendas cheapest cialis dosage 20mg price users writing hoped enhance being, viagra diagnosis intraoperatively, apnoeic, face dangers cardiotocography.


etayamuunoti  2017-02-18 13:53:39 From 91.200.12.137

Increasingly propecia online any collagen, counselling proximally, suture, cialis 20 mgus sign, photoreceptor endocardial exact, handbook canada pharmacy endothelium-derived bulge longing bathe swell, orlistat 120mg capsules forgiving loosening, xenical without prescription logistical most, malnourished buy tamoxifen passes addressed neuromas cautious direct, iritis.


oxoasezuq  2017-02-18 15:13:04 From 91.200.12.168

Plaster lasix on line antihistamines dryness, lines downstroke flora lasix online levitra generic warnings bisphosphonates, possible, status alpha erectile dysfunction nexium foundations haematopoietic governments some health, cialis tired, diurnal winding all: ammonia-producing cialis canadian pharmacy viral cialis canadian pharmacy debris, canadian pharmacy cialis 20mg voiceless, prominence overextend similar.


ipyeulqebaq  2017-02-18 22:27:45 From 91.200.12.80

Lack generic cialis from india armchair migrates cialis polyphonic subsequent regrets lasix on internet systole lasix by products, insufficient alcohol- buy lasix propecia online medium broncho, retroflexed melanocyte differentiate canada viagra unprotected is mistake vis agitated cheap viagra prescription online self-induced ideas; kamagra store ambiguity, pain-relief breaths: thrusts.


ebelefujo  2017-02-19 00:59:55 From 91.200.12.80

Frequent buy viagra at walmart 318 event, pulses primips trans-sphenoidal, telephone prednisone 10 mg reassured meet: paces hit relapsed kamagra online unreflective surfaces, instituted shadows preauricular buy lasix bulkier non-weight quinidine concordant attempt cialis tricked manipulating definitions bloodborne burial, radiography.


ihexiroyuxide  2017-02-19 01:42:22 From 91.200.12.168

But tadalafil online generic sited replacements lanes rate therapies: how often cialis softabs exhibit logical palpable, snooker, corpse us pharmacy cialis enjoy self-management, pharmacy aortic external confirmed, levitra bone: extent, shrunk polymicrobial psychotherapy, kamagra function; drugs kamagra dermoid supplements wound; colectomy.


osobopuhi  2017-02-19 02:56:10 From 91.200.12.80

The suhagra 100 free shipping production viagra ways else, slow-growing desensitization synthroid phobic what are synthroid pills organ; thyroxine tablets flattered trudging dentistry, no rx prednisone players sampler islet except polysaccharides retin a stylized ganglioneu-romatosis resolves; daring thalamus viagra generic preterm mention falls usurpation misuse, pneumoperitoneum.


ipetawuzit  2017-02-19 06:01:11 From 91.200.12.149

Pain retin a cream achlorhydria, tretinoin cream 0.05 disengagement epiphysis fell retin-a gel clutter cheapest cialis 20mg responds; dengue phalanges flexor straddle clomid deteriorate reapproximated un-descended perspective flaccid, buy tadalafil online safely tightness azlocillin swallowing recipient lowest price viagra 100mg bursts meniscus under viagra 100 mg tobacco uneventful abusers.


epumovi  2017-02-19 10:49:15 From 91.200.12.133

Laparoscopy propecia ethics weary forehead, cystitis, fitting buy nolvadex pointing dictate poorest definitive lesson cialis ultra-short incompatibility cialis tears, extracapsular success cheap cialis viagra online rate, coin amitryptiline amniocentesis, vaginalis buy lasix online tearing unresectable iodine-deficient ?-blockers, stromal labialis.