Skip to content

Instantly share code, notes, and snippets.

@thuan1412
Created August 21, 2023 16:21
Show Gist options
  • Save thuan1412/e2cb1a38270c23d33d5c39b8925f8c12 to your computer and use it in GitHub Desktop.
Save thuan1412/e2cb1a38270c23d33d5c39b8925f8c12 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"fmt"
"time"
)
func handle(ctx context.Context, name string) {
for {
select {
case <-ctx.Done():
return
case <-time.After(time.Second * 3):
fmt.Println("hello", name)
return
}
}
}
func main() {
var name string
var cancel context.CancelFunc
for {
fmt.Println("input your name:")
fmt.Scanln(&name)
// cancel the previous goroutine when we receive new input
if cancel != nil {
cancel()
}
var ctx context.Context
ctx, cancel = context.WithCancel(context.Background())
go handle(ctx, name)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment