亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

訪問 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 關注
  • 127 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號