Permalink
Browse files

add a tech demo for forever goroutine

  • Loading branch information...
1 parent 757b29f commit 957a1146ce5a01828e70e0b17badd45343411f05 @kicool committed Mar 13, 2012
Showing with 41 additions and 0 deletions.
  1. +41 −0 forever/forever.go
View
@@ -0,0 +1,41 @@
+package main
+
+/*
+ * demo a way to write a daemon
+ */
+import (
+ "os"
+)
+
+// Receives the change in the number of goroutines
+var goroutineDelta = make(chan int)
+var needToCreateANewGoroutine = true
+
+func main() {
+ go forever()
+
+ numGoroutines := 0
+ for diff := range goroutineDelta {
+ numGoroutines += diff
+ if numGoroutines == 0 {
+ os.Exit(0)
+ }
+ }
+}
+
+// Conceptual code
+func forever() {
+ for {
+ if needToCreateANewGoroutine {
+ // Make sure to do this before "go f()", not within f()
+ goroutineDelta <- +1
+
+ go f()
+ }
+ }
+}
+
+func f() {
+ // When the termination condition for this goroutine is detected, do:
+ goroutineDelta <- -1
+}

0 comments on commit 957a114

Please sign in to comment.