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

OR channel using context #9

Open
shiva0612 opened this issue Dec 21, 2022 · 0 comments
Open

OR channel using context #9

shiva0612 opened this issue Dec 21, 2022 · 0 comments

Comments

@shiva0612
Copy link

package main

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

var (
	sleep_time = []int{1, 2, 3, 4}
)

func main() {
	create_n_goroutines_wait_until_one_is_done_and_exit(4)
}

func create_n_goroutines_wait_until_one_is_done_and_exit(n int) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	for i := 0; i < n; i++ {
		go work(i, cancel)
	}
	<-ctx.Done()
}

func work(i int, cancel context.CancelFunc) {
	defer cancel()
	time.Sleep(time.Duration(sleep_time[i]) * time.Second)
	fmt.Println("DONE by index: ", i)
}
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