访问 URL 时终止 go routine

我使用 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)

    }

}


一只斗牛犬
浏览 93回答 1
1回答

犯罪嫌疑人X

你可以通过使用时间自动收报机和上下文来实现func read_serial_port(c context.Context){&nbsp; &nbsp; c := &serial.Config{Name:"/dev/ttyACM0", Baud:9600}&nbsp; &nbsp; s, err := serial.OpenPort(c)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatal(err)&nbsp; &nbsp; }&nbsp; &nbsp; filename:= randSeq(10)+".txt"&nbsp; &nbsp; file, _ := os.Create("output/"+filename)&nbsp; &nbsp; defer file.Close();&nbsp; &nbsp; ticker := time.NewTicker(100 * time.Millisecond)&nbsp; &nbsp; defer ticker.Stop()&nbsp; &nbsp; for{&nbsp; &nbsp; &nbsp; &nbsp; select {&nbsp; &nbsp; &nbsp; &nbsp; case <-c.Done():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; case <-ticker.C:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; buf := make([]byte, 128)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; n, err := s.Read(buf)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Fatal(err)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Printf("%s", string(buf[:n]))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Fprintf(file, string(buf[:n]))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; time.Sleep(100 * time.Millisecond)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}然后你需要添加另一条路线来调用取消功能if r.FormValue("action") == "add"{&nbsp; &nbsp; c, cnl := context.WithCancel(context.Background())&nbsp; &nbsp; // need to access this cancel function to use it in another route&nbsp; &nbsp; ExportedFunction = cnl&nbsp; &nbsp; go read_serial_port()}然后通过以下方式取消它:func abortingMission(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; ExportedFunction()}也不要在你的函数名中使用下划线
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go