简体   繁体   English

完成wg.wait()后停止询问输入的选项

[英]Option to stop asking for input after wg.wait() is done

1 . 1 I triggered a goroutine (which runs a third party program) and I am using wg.Wait() to wait for it to complete 我触发了一个goroutine(运行第三方程序),我正在使用wg.Wait()等待它完成

2 . 2 Before wg.Wait() , I want to provide user an option to cancel this third party program that is running (if he want to) wg.Wait()之前,我想为用户提供一个选项来取消正在运行的第三方程序(如果他愿意的话)

3 . 3 After the third party program execution is done, this user input option should vanish off (there is no reason why he should stop the process thats already done). 第三方程序执行完成后,此用户输入选项应该消失(没有理由他应该停止已经完成的过程)。 Currently this input has to be provided before wg.Wait() is triggered 目前,必须在触发wg.Wait()之前提供此输入

How can I do it? 我该怎么做? I thought of keeping the optiontoStop() function in goroutine and then kill it after wg.Wait() is done but I wasn't able to get it done or else is there a way to send a random value to the blocking call of scanf before I return from XYZ? 我想在goroutine中保留optiontoStop()函数然后在wg.Wait()完成之后将其杀死但是我无法完成它或者是否有办法将随机值发送到scanf的阻塞调用我从XYZ回来之前? or any other workarounds? 或任何其他解决方法?

More details: 更多细节:

1 . 1

func XYZ() {
   wg.Add(1)
   go doSomething(&wg) // this runs a third party program
}

2 . 2

func ABC() {
   XYZ()
   optiontoStop() // I want this input wait request to vanish off after 
                  // the third party program execution                    
                  // (doSomething()) is completed
   wg.Wait() 
   //some other stuff 
}

3 . 3

func optiontoStop() {
   var option string
   fmt.Println("Type 'quit'  if you want to quit the program")
   fmt.Scanf("%s",&string)
   //kill the process etc.
 }

You have to handle your user input in another Go routine, then instead of wg.Wait() , probably just use a select: 你必须在另一个Go例程中处理你的用户输入,然后代替wg.Wait() ,可能只需使用select:

func ABC() {
    done := make(chan struct{})
    go func() {
        defer close(done)
        doSomething()
    }()
    stop := make(chan struct{})
    go func() {
        defer close(stop)
        stop <- optionToStop()
    }
    select {
    case done:
        // Finished, close optionToStop dialog, and move on
    case stop:
        // User requested stop, terminate the 3rd party thing and move on
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM