Created
August 21, 2023 16:21
-
-
Save thuan1412/e2cb1a38270c23d33d5c39b8925f8c12 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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