Saturday, April 27, 2024
HomeGolangMethods to handle goroutine in case of webserver and longer working course...

Methods to handle goroutine in case of webserver and longer working course of – Getting Assist


Difficulty is Talked about on stackoverflow

I’ve a program that’s rtsp cameras to hls format utilizing ffmpeg for streaming. creating goroutines for every rtsp hyperlink as ffmpeg runs in background

Streams are added by following code.

func StreamProcess(information <-chan StreamData, ctx context.Context) {
for v := vary information {
    ctx, _ := context.WithCancel(ctx)
    go func() {
        if !getStreams(v.camera_id) {
            var stream StreamState
            stream.camera_id = v.camera_id
            stream.state = true
            go Stream(v, ctx)
            wg.Wait()
        } else {
            return
        }
    }()
}   

}

Streaming operate which runs ffmpeg command.

func Stream(meta StreamData, ctx context.Context) error {
    log.Println("Began Streaming")
    ffmpegCmd := exec.Command("ffmpeg", "-i", meta.rtsp, "-pix_fmt", "yuv420p", "-c:v", "libx264", "-preset", "ultrafast", "-b:v", "600k", "-c:a", "aac", "-b:a", "160k", "-f", "rtsp", fmt.Sprintf("rtsp://localhost:8554/%s", meta.camera_id))
    output, _ := ffmpegCmd.CombinedOutput()

    log.Println(string(output))

    for {
        choose {
        case <-ctx.Accomplished():
           log.Println("killing course of")
           ffmpegCmd.Course of.Kill()
           return nil
        }
    }}

my Objective is to cease every os.exec course of (ffmpeg command) or not less than shut all goroutines which might be below ffmpeg instructions with out closing fiber server.

Hello @Nitin_Kalmaste ,

I believe there may be an error within the StreamProcess: for every merchandise in information you launch a brand new goroutine, and this goroutine checks if getStreams returns true or false and does one thing primarily based on it. Have a look at what occurs if getStream returns false for a given merchandise – you create a brand new streamState variable, fill in its values, however then you don’t make use of it, it’s not getting used anythere – most definitely it is advisable use it for one thing.

Again to your query: while you shut the context, every Stream goroutine will return due to case <-ctx.Accomplished. If you wish to shut them with out closing the context, merely add an additional chan parameter to the Stream methodology, and examine if that channel is closed just like the way you examine ctx.Accomplished. The choose may have then 2 instances, one is the ctx.Accomplished and the opposite is the channel.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments