Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Go中如何使用context实现超时控制? #27

Open
qloog opened this issue Oct 25, 2020 · 0 comments
Open

Go中如何使用context实现超时控制? #27

qloog opened this issue Oct 25, 2020 · 0 comments

Comments

@qloog
Copy link
Contributor

qloog commented Oct 25, 2020

正常执行代码示例

package main

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

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

	done := make(chan int, 1)

	// do work
	go func() {
		fmt.Println("do working")
		time.Sleep(time.Second)

		// work done
		done <- 1
	}()

	select {
	case <-ctx.Done():
		fmt.Println(ctx.Err())
	case <-done:
		fmt.Println("work done on time")
	}

	fmt.Println("main func exit")
}

输出结果

do working
work done on time
main func exit

超时示例

package main

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

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

	done := make(chan int, 1)

	// do work
	go func() {
		fmt.Println("do working")
		//time.Sleep(time.Second)
		// 超时
		time.Sleep(time.Second*3)

		// work done
		done <- 1
	}()

	// 阻塞,等待
	select {
	// 统一超时处理
	case <-ctx.Done():
		fmt.Println(ctx.Err())
	case <-done:
		fmt.Println("work done on time")
	}

	fmt.Println("main func exit")
}

执行结果

do working
context deadline exceeded
main func exit
@qloog qloog changed the title Go中如何使用context实现并发控制? Go中如何使用context实现超时控制? Oct 25, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant