Skip to content

Commit

Permalink
add: go context
Browse files Browse the repository at this point in the history
  • Loading branch information
hthuz committed Jul 4, 2024
1 parent c166663 commit d0faf0a
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
32 changes: 32 additions & 0 deletions go/context/context.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package main

import (
"context"
"fmt"
"time"
)

func main() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()

go performTask(ctx)

select {
case <-ctx.Done():
fmt.Printf("%T\n", ctx)
fmt.Println(ctx)
fmt.Printf("%T\n", ctx.Done())
fmt.Println(ctx.Done())
fmt.Println("Task timeout")
}
}

// If performTask is not finished within 2 seconds, the program terminates
func performTask(ctx context.Context) {
select {
case <-time.After(5 * time.Second):
fmt.Println("Task completed")
}

}
31 changes: 31 additions & 0 deletions go/contextCancel/contextCancel.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package main

import (
"context"
"fmt"
"time"
)

func main() {
ctx, cancel := context.WithCancel(context.Background())

go task(ctx)

time.Sleep(2 * time.Second)
cancel()
time.Sleep(1 * time.Second)
}

func task(ctx context.Context) {
for {
select {
case <-ctx.Done():
fmt.Println("Task terminated")
return
default:
fmt.Println("Doing task")
time.Sleep(300 * time.Millisecond)
}
}

}

0 comments on commit d0faf0a

Please sign in to comment.