Skip to content

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

@qloog

Description

@qloog

正常执行代码示例

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions