diff --git a/concurrency/channels.go b/concurrency/channels.go new file mode 100644 index 0000000..bced12d --- /dev/null +++ b/concurrency/channels.go @@ -0,0 +1,17 @@ +package main + +import "fmt" + +func producer(ch chan string) { + ch <- "Message from Producer" + close(ch) +} + +func main() { + ch := make(chan string) + go producer(ch) + + for msg := range ch { + fmt.Println(msg) + } +} diff --git a/concurrency/goroutines.go b/concurrency/goroutines.go new file mode 100644 index 0000000..bf3fe2f --- /dev/null +++ b/concurrency/goroutines.go @@ -0,0 +1,20 @@ +// Praticando o paralelismo com go. + +package main + +import ( + "fmt" + "time" +) + +func printMessage(msg string) { + for i := 0; i < 5; i++ { + fmt.Println(msg) + time.Sleep(500 * time.Millisecond) + } +} + +func main() { + go printMessage("Hello from Goroutine!") + printMessage("Hello from Main!") +} diff --git a/concurrency/select.go b/concurrency/select.go new file mode 100644 index 0000000..610b77c --- /dev/null +++ b/concurrency/select.go @@ -0,0 +1,30 @@ +package main + +import ( + "fmt" + "time" +) + +func main() { + ch1 := make(chan string) + ch2 := make(chan string) + + go func() { + time.Sleep(1 * time.Second) + ch1 <- "Message from Channel 1" + }() + + go func() { + time.Sleep(2 * time.Second) + ch2 <- "Message from Channel 2" + }() + + for i := 0; i < 2; i++ { + select { + case msg1 := <-ch1: + fmt.Println(msg1) + case msg2 := <-ch2: + fmt.Println(msg2) + } + } +}