Skip to content

Instantly share code, notes, and snippets.

@SethBuilder
Last active November 24, 2022 06:38
Show Gist options
  • Save SethBuilder/194406a72ca8c421c73a6215c4c271d5 to your computer and use it in GitHub Desktop.
Save SethBuilder/194406a72ca8c421c73a6215c4c271d5 to your computer and use it in GitHub Desktop.
This is a GoLang exercise: a. Create two go-routines, which are running a loop with 10 iterations. Find a way to make the execution slower. b. How do you get data from those routines in the “main thread” ? c. Receive 10 individual strings from each go-routine. d. Find a way to stop the running go-routines from the “main thread”
package main
import (
"fmt"
"sync"
"time"
)
var wg sync.WaitGroup
func checkPanic(i int) {
panicInTheMiddle := false
// Uncomment to stop running routines when routines reach halfway through (answer for question d)
// panicInTheMiddle = true
if i == 5 && panicInTheMiddle {
panic("Panic in the middle panic")
}
}
func cleanup() {
defer wg.Done()
if r := recover(); r != nil {
fmt.Println("Recover in cleanup:", r)
}
}
func dayGreet() {
defer cleanup()
for i := 0; i < 10; i++ {
time.Sleep(time.Second)
fmt.Println("Good Morning")
checkPanic(i)
}
}
func eveningGreet() {
defer cleanup()
for i := 0; i < 10; i++ {
time.Sleep(time.Second)
fmt.Println("Good Evening")
checkPanic(i)
}
}
func main() {
wg.Add(1)
go dayGreet()
wg.Add(1)
go eveningGreet()
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment