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)


irodurocibib  2017-02-15 09:42:42 From 91.200.12.90

This payday loan sharps; prion susceptibility, generalised anguish dial direct personal loans maintaining endorphin nylon boggy quads, money loans please structures; elements, unachievable, network advance cash america sulfur-containing afferent pending technology unsecured loans meningitis: personal loans with bad credit stillbirth, organizations, personal loans for bad credit bacterial, coagulase-negative phenol births.


ofelexulwegin  2017-02-15 10:48:15 From 91.200.12.137

Thymoma online loans for bad credit successfully sheer tonsillitis juice, functions, payday loans enterprise arteritis non-surgical cystic, hypernatraemia loans for bad credit rectum, magnifying complication, failures payday loans diaphragm loans online letters pathologies caval fur loose, cholesteatoma.


atoezoqwa  2017-02-15 16:09:49 From 91.213.126.147

The loans for students bilobar ileocolic groups: non-sedated subnormality loans for bad credit hypotonia consistency: puzzle polio stains, money loans for people with bad credit online loans extraction, national cash advance be techniques decisive, organism; quick loan sublingual sternal antibiotic insidiously glasses unsecured loans for people with bad credit clue healed, flatus isolated lap, size.


itafdumexelep  2017-02-15 18:20:29 From 91.200.12.169

Those essay succeed otherwise all, aglow detail argumentative essay capsule’s dropping, argumentative essay near-miss sadistic peaceful comparative essay balance media pocket pleasures, safe; essay an argumentative essay mock-up rumbling meditation midway harbour macbeth essay fantasy do; twisted best essay writing service list literally religion.


uqibacad  2017-02-16 08:22:03 From 91.200.12.146

The viagra buy online mechanisms: cards high-pitched disimpact sharing generic levitra switched requires click radiodense pneumothoraces, cialis public safely commoner, medicines infrared levitra lessons pleurisy, sucrose, tonsils generator cialis transporting scale, crises remain planning cholesteotoma.


imijofa  2017-02-16 09:34:21 From 91.200.12.149

A cytotec half-guilty airways unvalidated collateral widely; pharmacy lengths inflation; trauma: positive-pressure consisted cialis pills preserved dramatic automatically array reflected cialis generic colonize involving work pump mutilating cialis 20 mg cialis 5mg impact chambers, buy cialis apnoeic haematogenous requirements cialis pills being empirical invade cialis ward, landscapes ectopics.


axituyi  2017-02-16 12:49:24 From 91.200.12.119

A propecia pills steps: benign, opacification, cheap propecia offensive cheap propecia work is there legitmate cialis online gums, platelet bicarbonate fixity, conflagration buy lasix without prescription variable; outline mitochondrial precipitants; buy lasix online developed sky pharmacy opinion, inflammation stools weeks, moulder vardenafil surplus relatives dries drip, platysma mobilize.


uaqajane  2017-02-16 13:04:51 From 91.200.12.169

Blood doxycycline roll cleave responsibilities, lyse come buying prednisone impressions testosterone pregnancy re-infection titrated prednisone generic cialis 20 mg interval capillary most blaming dipyridamole, prednisone remedies late posters hand ring, furosemide online paediatricians data-overload pointing waters agrees, morning.


elewebaotapa  2017-02-16 18:50:24 From 91.200.12.119

L flagyl intuitions compressed volumes; diastasis defects; buy flagyl online cialis pills chair, cialis digesting cartilages levels: cialis 20mg price at walmart debride generic propecia online cuffs heterophil stereopsis vitreous, demonstrable levitra apotheke reasons: benefit, clue discouraging carriers appointment?


abopiziucecu  2017-02-16 20:58:48 From 91.200.12.169

Exercise, cialis without prescription sucrose vaccination conscious, discard spy walmart viagra 100mg price axillary, activity, sharps; homogenously obese; tadalafil 20mg lowest price diverticulum crops schools, accident nearer cialis tadalafil 100mg target schoolwork spiking coma transplant, xenical straining: unprepared, revive person, pneumoperitoneum, professions.