dsy48837 2016-08-20 17:59
浏览 67
已采纳

我应该使用通道还是sync.Mutex lock()?

While doing a go test -race, I found that a call to os.Process.Kill, was made before the command started cmd.Start(), I came with to posible solutions, one to use a channel:

package main

import "os/exec"

func main() {
    cmd := exec.Command("sleep", "10")
    started := make(chan struct{}, 1)

    go func() {
        <-started
        cmd.Process.Kill()
    }()

    if err := cmd.Start(); err != nil {
        panic(err)
    }
    started <- struct{}{}

    cmd.Wait()
}

or to use a lock:

package main

import (
    "os/exec"
    "sync"
)

func main() {
    var lock sync.Mutex
    cmd := exec.Command("sleep", "10")

    lock.Lock()
    if err := cmd.Start(); err != nil {
        panic(err)
    }
    lock.Unlock()
    go func() {
        cmd.Process.Kill()
    }()

    cmd.Wait()
}

Both options work but wondering what could be the most idiomatic or better approach, while the main goal is just to prevent killing a process that hasn't been started.

  • 写回答

1条回答 默认 最新

  • douzhen1234 2016-08-20 18:13
    关注

    I would suggest you use a channel, but let me point out something about your code.

    I noticed you used a buffered channel, and then sent data on that channel first, before calling the goroutine that consumes the channel. In my opinion, it would be better to:

    1) use an unbuffered channel for signalling, especially in this case.

    2) Have the goroutine be responsible for starting the process and calling wait, while signaling to the main that it has started.

    Like this:

    package main
    
    import "os/exec"
    
    func main() {
    
        cmd := exec.Command("sleep", "10")
        started := make(chan struct{})
    
        go func(cmd *exec.Cmd, signal chan struct{}) {
            if err := cmd.Start(); err != nil {
                panic(err)
            }
    
            started <- struct{}{}
            cmd.Wait()
        }(cmd, started)
    
        <-started
        cmd.Process.Kill()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测