Last active
December 17, 2016 17:13
-
-
Save arosh/f51651418ec6f320366d1176de0e3335 to your computer and use it in GitHub Desktop.
goroutine cancel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
func main() { | |
cancel := make(chan struct{}) | |
go func() { | |
time.Sleep(3 * time.Second) | |
fmt.Println("Cancel!") | |
cancel <- struct{}{} | |
// close(cancel) is also OK! | |
}() | |
wasCanceled := func() bool { | |
select { | |
case <-cancel: | |
return true | |
default: | |
return false | |
} | |
} | |
i := 1 | |
for { | |
if wasCanceled() { | |
break | |
} | |
fmt.Printf("i = %v\n", i) | |
time.Sleep(100 * time.Millisecond) | |
i += 1 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment