Last active
January 31, 2019 21:56
-
-
Save fmassicano/14b2cc70c267db27b56702e48414c90f to your computer and use it in GitHub Desktop.
Golang practicing code
This file contains hidden or 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" | |
) | |
var ( | |
done = make(chan bool) | |
i int = 0 | |
) | |
func say(s string, n int) { | |
for i := 0; i < n; i++ { | |
time.Sleep(100 * time.Millisecond) | |
fmt.Println(s) | |
} | |
} | |
func wrapSays(s string, n int){ | |
i ++ | |
go func(){say(s,n); done <- true}() | |
} | |
func Done(){ | |
for j := 0 ; j < i ; j++ {<- done;}; fmt.Print("DONE!!!") | |
} | |
func main() { | |
defer Done() | |
wrapSays("a", 4) | |
wrapSays("b", 5) | |
wrapSays("d", 5) | |
} |
This file contains hidden or 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" | |
func fibonacci(c, quit chan int) { | |
x, y := 0, 1 | |
for { // infinit loop until 'quit' channel to be updated | |
select { | |
case c <- x: // each time that request <-c this case will be executed | |
x, y = y, x+y | |
case <-quit: // wait for 'quit' to be updated | |
fmt.Println("quit") | |
return | |
} | |
} | |
} | |
func main() { | |
// define a channel 'c' to store the result of fibonacci | |
c := make(chan int) | |
// define a channel 'quit' to alert the process was finished | |
quit := make(chan int) | |
// define a goroutine that will print 10 fibonacci numbers | |
go func() { | |
for i := 0; i < 10; i++ { | |
fmt.Println(<-c) // request the channel value 'c' ["print 10 receivers c"] | |
} | |
quit <- 0 // send 0 to channel quit to finish the program | |
}() | |
fibonacci(c, quit) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment