Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何向goroutine发出停止跑步的信号?_Go - Fatal编程技术网

如何向goroutine发出停止跑步的信号?

如何向goroutine发出停止跑步的信号?,go,Go,我正试图停止一个循规蹈矩,但我找不到实现这一点的方法。我想用第二个频道,但如果我从中读到,它会阻止它,不是吗?。这里有一些代码,我希望能解释我要做的事情 package main import "fmt" import "time" func main() { var tooLate bool proCh := make(chan string) go func() { for { fmt.Println("work

我正试图停止一个循规蹈矩,但我找不到实现这一点的方法。我想用第二个频道,但如果我从中读到,它会阻止它,不是吗?。这里有一些代码,我希望能解释我要做的事情

package main

import "fmt"
import "time"

func main() {

    var tooLate bool

    proCh := make(chan string)

    go func() {
        for {
               fmt.Println("working")
        //if is tooLate we stop/return it
            if tooLate { 
            fmt.Println("stopped")
                return
            }
       //processing some data and send the result on proCh
            time.Sleep(2 * time.Second)
            proCh <- "processed"
            fmt.Println("done here")

        }
    }()
    select {
    case proc := <-proCh:
        fmt.Println(proc)
    case <-time.After(1 * time.Second):
        // somehow send tooLate <- true
        //so that we can stop the go routine running
        fmt.Println("too late")
    }

    time.Sleep(4 * time.Second)
    fmt.Println("finish\n")
}
主程序包
输入“fmt”
导入“时间”
func main(){
图拉特布尔酒店
proCh:=制造(成串)
go func(){
为了{
fmt.Println(“工作”)
//如果是tooLate,我们将停止/退回它
如果tooLate{
fmt.Println(“停止”)
返回
}
//处理一些数据并将结果发送到proCh
时间。睡眠(2*时间。秒)

proCh实现这一点的方法很少,最简单、最方便的方法是使用另一个通道,如:

func main() {
    tooLate := make(chan struct{})
    proCh := make(chan string)

    go func() {
        for {
            fmt.Println("working")
            time.Sleep(1 * time.Second)
            select {
            case <-tooLate:
                fmt.Println("stopped")
                return
            case proCh <- "processed": //this why it won't block the goroutine if the timer expirerd.
            default: // adding default will make it not block
            }
            fmt.Println("done here")

        }
    }()
    select {
    case proc := <-proCh:
        fmt.Println(proc)
    case <-time.After(1 * time.Second):
        fmt.Println("too late")
        close(tooLate)
    }

    time.Sleep(4 * time.Second)
    fmt.Println("finish\n")
}
func main(){
tooLate:=make(chan结构{})
proCh:=制造(成串)
go func(){
为了{
fmt.Println(“工作”)
时间。睡眠(1*时间。秒)
挑选{

case为什么我们需要
case proCh@AnthonyHat否,因为在
case@OneOfOne之后,如果计时器过期,goroutine只会返回
case@AnthonyHat
默认值:
在select中使其成为非阻塞,当您注释
close(tooLate)
时,您这样做
case为什么使chan类型结构{}?可能的副本