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 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题