0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

goroutineに制限時間を加える

Posted at

間に合わなかった場合


package main

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

func task(ctx context.Context, channel_kun chan string) {
	fmt.Println("start")
	time.Sleep(5 * time.Second)
	fmt.Println("finish")
	channel_kun <- "良くできました"
}

func main() {
	channel_kun := make(chan string)
	ctx := context.Background()
	time_limit := 3 * time.Second
	fmt.Println("制限時間は", time_limit, "ね~")

	ctx, cancel := context.WithTimeout(ctx, time_limit)
	defer cancel()
	go task(ctx, channel_kun)

loop_label:
	for {
		select {
		case <-ctx.Done():
			fmt.Println("時間切れ~")
			fmt.Println(ctx.Err())
			break loop_label
		// タスクが間に合った時。
		case message := <-channel_kun:
			fmt.Println("間に合いました")
			fmt.Println(message)
			break loop_label
		}
	}
	fmt.Println("for文を終了します。")
}


実行結果


制限時間は 3s ね~
start
時間切れ~
context deadline exceeded
for文を終了します。

間に合った場合


package main

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

func task(ctx context.Context, channel_kun chan string) {
	fmt.Println("start")
	time.Sleep(2 * time.Second)
	fmt.Println("finish")
	channel_kun <- "良くできました"
}

func main() {
	channel_kun := make(chan string)
	ctx := context.Background()
	time_limit := 5 * time.Second
	fmt.Println("制限時間は", time_limit, "ね~")

	ctx, cancel := context.WithTimeout(ctx, time_limit)
	defer cancel()
	go task(ctx, channel_kun)

loop_label:
	for {
		select {
		case <-ctx.Done():
			fmt.Println("時間切れ~")
			fmt.Println(ctx.Err())
			break loop_label
		// タスクが間に合った時。
		case message := <-channel_kun:
			fmt.Println("間に合いました")
			fmt.Println(message)
			break loop_label
		}
	}
	fmt.Println("for文を終了します。")
}



実行結果


制限時間は 5s ね~
start
finish
間に合いました
良くできました
for文を終了します。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?