为了账号安全,请及时绑定邮箱和手机立即绑定

访问 URL 时终止 go routine

访问 URL 时终止 go routine

Go
一只斗牛犬 2023-04-17 15:07:54
我使用 Go 制作了一个简单的网络应用程序。有一个goroutine当用户访问 URL 时执行的,比方说/inspection/start/。goroutine当用户访问 URL 时如何停止/inspection/stop/?我听说过,channel但我不确定在我的情况下该怎么做。这是代码:func inspection_form_handler(w http.ResponseWriter, r *http.Request) {    if r.FormValue("save") != "" {        airport_id := getCurrentAirportId(r)        r.ParseForm()        if airport_id != nil {            if r.FormValue("action") == "add"{                go read_serial_port()            }            // redirect back to the list            http.Redirect(w, r, "/airport#inspect", http.StatusSeeOther)        }    }}常规功能func read_serial_port(){    c := &serial.Config{Name:"/dev/ttyACM0", Baud:9600}    s, err := serial.OpenPort(c)    if err != nil {        log.Fatal(err)    }    filename:= randSeq(10)+".txt"    file, _ := os.Create("output/"+filename)    defer file.Close();    for{        buf := make([]byte, 128)        n, err := s.Read(buf)        if err != nil {            log.Fatal(err)        }        log.Printf("%s", string(buf[:n]))        fmt.Fprintf(file, string(buf[:n]))        time.Sleep(100 * time.Millisecond)    }}
查看完整描述

1 回答

?
犯罪嫌疑人X

TA贡献2080条经验 获得超4个赞

你可以通过使用时间自动收报机和上下文来实现


func read_serial_port(c context.Context){

    c := &serial.Config{Name:"/dev/ttyACM0", Baud:9600}

    s, err := serial.OpenPort(c)


    if err != nil {

        log.Fatal(err)

    }


    filename:= randSeq(10)+".txt"

    file, _ := os.Create("output/"+filename)


    defer file.Close();


    ticker := time.NewTicker(100 * time.Millisecond)

    defer ticker.Stop()


    for{

        select {

        case <-c.Done():

            break

        case <-ticker.C:

            buf := make([]byte, 128)

            n, err := s.Read(buf)


            if err != nil {

                log.Fatal(err)

            }


            log.Printf("%s", string(buf[:n]))


            fmt.Fprintf(file, string(buf[:n]))


            time.Sleep(100 * time.Millisecond)

        }

    }

}

然后你需要添加另一条路线来调用取消功能


if r.FormValue("action") == "add"{

    c, cnl := context.WithCancel(context.Background())

    // need to access this cancel function to use it in another route

    ExportedFunction = cnl

    go read_serial_port()

}

然后通过以下方式取消它:


func abortingMission(w http.ResponseWriter, r *http.Request) {

    ExportedFunction()

}

也不要在你的函数名中使用下划线


查看完整回答
反对 回复 2023-04-17
  • 1 回答
  • 0 关注
  • 73 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信