douzhi9939 2018-10-13 13:47
浏览 44
已采纳

如何运行goroutine的单个实例

I have a goroutine that will be run multiple times. But it can only run one at a time (single instance). What is the correct/idiomatic way to make sure a certain goroutine can run only one at a time?

Here is my contrived example code to illustrate the point:

func main() {
    // Contrived example!!!!!!
    // theCaller() may be run at multiple, unpredictable times
    // theJob() must only be run one at a time
    go theCaller()
    go theCaller()
    go theCaller()
}

func theCaller() {
    if !jobIsRunning { // race condition here!
        jobIsRunning = true
        go theJob()
    }
}

var jobIsRunning bool

// Can run multiple times, but only one at a time
func theJob() {
    defer jobDone()
    do_something()
}

func jobDone() {
    jobIsRunning = false
}
  • 写回答

1条回答 默认 最新

  • dtah63820 2018-10-13 14:00
    关注

    Based on question and other comments from the OP, it looks like the goal is to start a new job if and only if a job is not already running.

    Use a boolean variable protected by a sync.Mutex to record the running state of of the job. Set the variable to true when starting a job and to false when the job completes. Test this variable to determine if a job should be started.

    var (
        jobIsRunning   bool
        JobIsrunningMu sync.Mutex
    )
    
    func maybeStartJob() {
        JobIsrunningMu.Lock()
        start := !jobIsRunning
        jobIsRunning = true
        JobIsrunningMu.Unlock()
        if start {
            go func() {
                theJob()
                JobIsrunningMu.Lock()
                jobIsRunning = false
                JobIsrunningMu.Unlock()
            }()
        }
    }
    
    func main() {
        maybeStartJob()
        maybeStartJob()
        maybeStartJob()
    }
    

    The lower-level sync/atomic package can also be used and may have better performance than using a mutex.

    var jobIsRunning uint32
    
    func maybeStartJob() {
        if atomic.CompareAndSwapUint32(&jobIsRunning, 0, 1) {
            go func() {
                theJob()
                atomic.StoreUint32(&jobIsRunning, 0)
            }()
        }
    }
    

    The sync/atomic package documentation warns that the functions in the package require great care to use correctly and that most applications should use the sync package.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示