Friday, March 29, 2024
HomeGolangLearn how to cease the fmt.Scanf course of operating underneath Goroutine? -...

Learn how to cease the fmt.Scanf course of operating underneath Goroutine? – Getting Assist


Howdy, I’m engaged on a program that occasions out and strikes to the subsequent course of if the consumer didn’t enter something within the console after a while. I adopted this publish whereas designing my program, nevertheless, this doesn’t actually cancel the method of fmt.Scanf and turns into problematic if there’s one other scanf after the timeout.

I created a modified model of the code which asks for a brand new enter after the timeout:

func most important() {
	ch := make(chan int)

	go func() {
		var age int
		fmt.Printf("Your age: ")
		fmt.Scanf("%d", &age)
		fmt.Println("Age: ", age)
		ch <- 1
	}()

	choose {
	case <-ch:
		fmt.Println("Exiting.")
		os.Exit(0)
	case <-time.After(3 * time.Second):
		fmt.Println("nTimed out")

		var top int
		fmt.Printf("Your top: ")
		fmt.Scanf("%dn", &top)
		fmt.Println("Top: ", top)
	}
}

Listed below are some instance inputs:

As you may see, when it asks for the peak, it will get scanned from the age scanf, not the peak scanf. It’s because the age scanf remains to be lively.

Now my query is, how do I cease the method of the primary scanf? Or is there another solution to learn consumer enter that doesn’t wait and block till the consumer entered one thing within the console?

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments