For a presentation, I made a program trying to illustrate how you can make a program that is concurrent and runs in parallel using Go. The output appears to show that it is at least running concurrently, but I'm not sure how to tell if it's running in parallel. I've read through a lot of resources on how to use goroutines and sync them together in a WaitGroup, but there seems to be a lot of confusion on whether these run on separate threads. As a novice programmer that's especially new to Go, I would greatly appreciate some clarification!
package main
import (
"fmt"
"sync"
"time"
)
//take order
func takeOrder1(wg *sync.WaitGroup) {
s_sleep(1000)
fmt.Println("\nTaking order...", t_time())
go takeOrder2(wg)
}
func takeOrder2(wg *sync.WaitGroup) {
s_sleep(1500)
fmt.Println("\nOrder tooken!", t_time())
wg.Done()
}
//make fires
func makeFries1(wg *sync.WaitGroup) {
s_sleep(1500)
fmt.Println("\nFrying fries...", t_time())
go makeFries2(wg)
}
func makeFries2(wg *sync.WaitGroup) {
s_sleep(3000)
fmt.Println("\nFries Fried!", t_time())
wg.Done()
}
//burn burger
func makeBurger1(wg *sync.WaitGroup) {
s_sleep(2000)
fmt.Println("\nFlipping burger...", t_time())
go makeBurger2(wg)
}
func makeBurger2(wg *sync.WaitGroup) {
s_sleep(5000)
fmt.Println("\nCooked a burger!", t_time())
wg.Done()
}
//cook drink
func pourDrink1(wg *sync.WaitGroup) {
s_sleep(1000)
fmt.Println("\nPutting ice in cup...", t_time())
go pourDrink2(wg)
}
func pourDrink2(wg *sync.WaitGroup) {
s_sleep(3000)
fmt.Println("\nPouring soda in cup...", t_time())
go pourDrink3(wg)
}
func pourDrink3(wg *sync.WaitGroup) {
s_sleep(2500)
fmt.Println("\nDrink poured!", t_time())
wg.Done()
}
//wipe table
func cleanTable1(wg *sync.WaitGroup) {
s_sleep(1000)
fmt.Println("\n'Cleaning' table....", t_time())
go cleanTable2(wg)
}
func cleanTable2(wg *sync.WaitGroup) {
s_sleep(1500)
fmt.Println("\nTable 'clean'!", t_time())
wg.Done()
}
//delay
func s_sleep(x int) { time.Sleep(time.Duration(x) * time.Millisecond) }
//just to print time
func t_time() string {
return time.Now().Format("15:04:05")
}
//create array of tasks to complete
var McDolansTasks = []func(*sync.WaitGroup){
takeOrder1, makeFries1, makeBurger1, pourDrink1, cleanTable1}
//main function
func main() {
var waitGroup sync.WaitGroup
// Set number of effective goroutines we want to wait upon
waitGroup.Add(len(McDolansTasks))
for _, task := range McDolansTasks {
// Pass reference to WaitGroup instance
// Each of the tasks should call on WaitGroup.Done()
go task(&waitGroup)
}
// Wait until all goroutines have completed execution.
waitGroup.Wait()
println("\nClock out for the day!")
}