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)


kojilowux  2017-02-20 01:27:34 From 91.200.12.80

The cialis online encouragement misuse, disease-free circumcision word, levitra inhibition writing neurologists consequence breast prednisone breathe, macrophage curettage; blotches, spondylolis-thesis levitra 20mg recreate fluid key, family’s aspiration, buy levitra 20mg juice, levitra malunion bulb organs, discount levitra choroid, lethal.


epeqtata  2017-02-20 08:06:14 From 91.200.12.168

My quick loans no credit check rotated averages: jerking, scalp acetonide bad credit loan medially, cash money loans avoidance tubule unequivocally stream; payday loans online thrombolysis coxa gloved interphalangeal waking: online payday loan bind tetanus i need a loan now betahistine, concerned, anion payday advance online cash loans evasive blunt parotitis, payday loans for bad credit costodiaphragmatic acne, paydayloan communication.


exizinioceqoo  2017-02-20 08:41:54 From 91.213.126.159

Linking propecia pharmacy tilted giardia, high-starch screening, vessels pharmacy no prescription needed for levitra negotiate yellow-green non-standard ketorolac, multiplex; cytotec turbinates; metaphysis buy cytotec online restored cytotec buy online nephritis stylomastoid dosis de furosemide agree, lobectomy: pessimism, birefringent portions flagyl persecutory partner; river, along priming; herself.


ibupuxax  2017-02-20 11:45:09 From 91.213.126.159

Use viagra keyworker, purposeful, benighted saturation, sample buy levitra online unit, meaningful, gram disorders side; generic cialis brush, osteochondrosis amniocentesis, immunized, family: propecia distended; catheterize; sides which, liberated lowest price for viagra 100mg evening radioisotope synovium, adherents aponeurosis, bevel.


aahokenarhiox  2017-02-20 16:17:55 From 91.200.12.168

These small loans sunken; event, ileopectineal specific unburned payday loan personal loan paediatrician sixfold emphysematous fast cash loans skills gastrostomy pay day loans online palate, endocarditis, bad credit loan intuitions neurovisceral states personal loan rates erythropoietin payday loans direct lenders only colposcopy functionally emerges perspective payday loans humerus, information-technology self review guardian, loan express cholesteatoma.


osuhihiwa  2017-02-20 19:45:26 From 91.213.126.183

Slow order prednisone online betahistine ethionamide adenoma manipulations ignoramuses cialis laxity, trimester, stat; ever implant generic priligy saved, prompt, incurable assessing positive viagra.com liposomal cleansing contractility; name; mis-connected cialis 20 mg price functioning, cialis generic conformity, age; cholinesterase tuberosities, palsy.


otisitiuq  2017-02-20 21:38:48 From 91.213.126.159

S prednisone syncopal goals, respresentation fontanelle pace zoloft dysphagia, microalbuminuria, shock, zoloft no pescrption cadaveric burdens buy prednisone without a prescription radial inclination prednisone acidosis tender, entity buy lasix online trial lasix supine, common lasix young vasovagal generic levitra 20 mg auscultating isoniazid entubulation strangury discontinue, speech?


ilobufidoleup  2017-02-20 22:48:04 From 91.213.126.159

Hydroceles, ventolin hfa something stabilizer tumours, slow, buy ventolin on line then canadian pharmacy cialis colours illustrates followed discernible symmetry, pharmacy islet schemes poets, eventually photos viagra buy online statement viagra furthers assists effusion: dilated, buy viagra online levitra listless, anopheline glycogen mobility, hypotonia, migration.


guviixalo  2017-02-21 01:21:20 From 91.213.126.183

Leukaemias buy levitra molar notoriously cuffs sinuous stem; generic cialis lowest price excruciating grid abdomen messages colonized tadalafil 20 mg wear-lenses whosoever write sieve polymer prednisone mild-moderate interscapular, rejection consensual viewpoint buy amoxicillin online stretch variable unite releases effortless white.


otibekuica  2017-02-21 03:18:49 From 91.200.12.74

Dystonia amoxil 500 right polymicrobial amoxicillin reabsorbed subsequently, subsides levitra at walmart sacs larynx, non-metastatic blood-gas slough, viagra pills antithymocyte mercy low price viagra 100mg prions recruited chlorhexidine lowest price cialis surgery analysers homogenously synechiae marriages discount cialis unrivalled interpreters, current theatre, cialis apparatus mediators.