go runtime_error ai_generated true

panic: sync: Once 被重复使用

panic: sync: Once is reused

ID: go/once-reuse-panic

其他格式: JSON · Markdown 中文 · English
80%修复率
80%置信度
0证据数
2024-01-18首次发现

版本兼容性

版本状态引入弃用备注
1.19 active

根因分析

在 sync.Once 已被使用后再次尝试使用它,这是不允许的。

English

Attempting to reuse a sync.Once after it has been used, which is not allowed.

generic

解决方案

  1. 90% 成功率
    Use a flag with atomic operations to implement single execution: 
    
    var done int32
    go func() {
        if atomic.CompareAndSwapInt32(&done, 0, 1) {
            // do once
        }
    }()
  2. 85% 成功率
    Ensure Once is used only once per lifecycle, and create a new instance if needed.

无效尝试

常见但无效的做法:

  1. 90% 失败

    Copying a sync.Once is unsafe and can cause races; it's not designed to be copied.

  2. 40% 失败

    If the Once is embedded in a struct that's reused, it may still be copied.