Golang并发安全计时器实现详解
时间:2025-11-27 12:36:35 288浏览 收藏
Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《Golang并发安全计时器实现方法》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!
答案:Go中实现并发安全计时器可通过三种方式:使用sync.Mutex封装Timer操作,确保原子性;通过channel和独立goroutine管理Timer,避免共享状态;结合context实现生命周期控制,适配取消与超时场景。

在Go语言中实现并发安全的计时器,关键在于避免多个goroutine同时操作共享状态导致的数据竞争。虽然time.Timer本身不是并发安全的,但可以通过合理设计结构和使用同步机制来构建一个线程安全的计时器。
使用互斥锁保护Timer操作
最直接的方式是用sync.Mutex保护对time.Timer的读写操作,确保同一时间只有一个goroutine能操作定时器。
例如,封装一个可重置、可停止的安全计时器:
type SafeTimer struct {
mu sync.Mutex
timer *time.Timer
dur time.Duration
}
func NewSafeTimer(dur time.Duration) *SafeTimer {
return &SafeTimer{
timer: time.AfterFunc(dur, func() {}),
dur: dur,
}
}
func (st *SafeTimer) Reset() {
st.mu.Lock()
defer st.mu.Unlock()
if st.timer != nil {
st.timer.Stop()
}
st.timer = time.AfterFunc(st.dur, func() {
// 触发回调逻辑
})
}
func (st *SafeTimer) Stop() bool {
st.mu.Lock()
defer st.mu.Unlock()
if st.timer == nil {
return false
}
return st.timer.Stop()
}
利用channel和select实现完全协程安全的调度
更推荐的做法是通过一个独立的goroutine管理计时器,所有外部操作通过channel传递,彻底避免共享变量。
这种方式天然线程安全,且逻辑清晰:
type TimerManager struct {
resetCh chan bool
stopCh chan bool
done chan bool
dur time.Duration
}
func NewTimerManager(dur time.Duration) *TimerManager {
tm := &TimerManager{
resetCh: make(chan bool),
stopCh: make(chan bool),
done: make(chan bool),
dur: dur,
}
go tm.run()
return tm
}
func (tm TimerManager) run() {
var timer time.Timer
timer = time.AfterFunc(tm.dur, func() {
tm.done <- true
})
for {
select {
case <-tm.resetCh:
if !timer.Stop() {
select {
case <-timer.C:
default:
}
}
timer = time.AfterFunc(tm.dur, func() {
tm.done <- true
})
case <-tm.stopCh:
if !timer.Stop() {
select {
case <-timer.C:
default:
}
}
return
}
}}
func (tm *TimerManager) Reset() {
tm.resetCh <- true
}
func (tm *TimerManager) Stop() {
tm.stopCh <- true
}
func (tm *TimerManager) Done() <-chan bool {
return tm.done
}
使用context控制生命周期
结合context可以更优雅地管理计时器的生命周期,尤其适合需要取消或超时控制的场景。
将计时器嵌入到context中,外部通过context.Done()监听事件:
func StartSafeTimer(ctx context.Context, dur time.Duration, callback func()) context.CancelFunc {
timer := time.NewTimer(dur)
cancel := func() {
if !timer.Stop() {
select {
case <-timer.C:
default:
}
}
}
go func() {
select {
case <-timer.C:
callback()
case <-ctx.Done():
cancel()
}
}()
return cancel}
基本上就这些方法。第一种适合简单共享场景,第二种最安全且易扩展,第三种适合集成进现有context体系。选择哪种取决于你的具体需求和架构风格。
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
-
860 收藏
-
843 收藏
-
826 收藏
-
809 收藏
-
792 收藏
-
Golang · Go教程 | 28分钟前 | 错误处理 · Context · 并发控制 · Go教程 · 并发控制 Go教程 context取消 context.WithCancelCause context.Cause342 收藏
-
219 收藏
-
Golang · Go教程 | 18小时前 | HTTP · Go教程 · 问题排查 · io.ReadAll · JSON绑定 · Go教程 Go HTTP请求体 io.ReadAll Request Body JSON绑定244 收藏
-
Golang · Go教程 | 19小时前 | 跨域 · cors · options · Go教程 · net/http · 跨域 Access-Control-Allow-Origin 预检请求 Options Go教程 Go CORS275 收藏
-
Golang · Go教程 | 20小时前 | WaitGroup · 并发编程 · Go教程 · Go 1.25 · Go并发 WaitGroup errgroup Go 1.25 sync.WaitGroup.Go172 收藏
-
238 收藏
-
217 收藏
-
367 收藏
-
Golang · Go教程 | 5天前 | channel · select · Context · Go教程 · 性能排查 · select channel context default time.Ticker Go教程 CPU飙高 for select459 收藏
-
Golang · Go教程 | 6天前 | map · 基准测试 · 性能优化 · Go教程 · 内存分配 · 内存分配 Go性能优化 benchmark Go教程 map预分配 make map benchmem395 收藏
-
Golang · Go教程 | 6天前 | defer · 单元测试 · testing · Go教程 · t.Cleanup · defer 单元测试 Testing 子测试 Go教程 T.Cleanup 测试资源清理418 收藏
-
Golang · Go教程 | 6天前 | defer · Go教程 · 文件句柄 · 资源释放 · 数据库rows · defer for循环 文件句柄 资源释放 close Go教程 rows.Close421 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习