Skip to content

Instantly share code, notes, and snippets.

@CypherpunkSamurai
Created August 25, 2024 17:15
Show Gist options
  • Save CypherpunkSamurai/3981d03559336f4d2003c4a948159a8a to your computer and use it in GitHub Desktop.
Save CypherpunkSamurai/3981d03559336f4d2003c4a948159a8a to your computer and use it in GitHub Desktop.
Golang Coroutines Quickstart (https://www.youtube.com/watch?v=anACPPJCNVA)
package main
import (
"fmt"
"time"
)
func main() {
since := time.Now()
// cooking
foodList := []string{"mushroom pizza", "pasta", "kebab", "cake"}
for _, food := range foodList {
cook(food)
}
// time
fmt.Printf("took %.0f sec to cook\n", time.Since(since).Seconds())
}
// cook cook the food
func cook(food string) {
fmt.Printf("cooking %s\n", food)
time.Sleep(2 * time.Second)
}
/*
output:
took 8 second to cook
*/
package main
import (
"fmt"
"sync"
"time"
)
func main() {
since := time.Now()
// cooking
foodList := []string{"mushroom pizza", "pasta", "kebab", "cake"}
// create a WaitGroup for waiting for coroutines
var wg sync.WaitGroup
// add the number of tasks to wait for
wg.Add(len(foodList))
for _, food := range foodList {
// use a simple coroutine (this will fail as we do not wait for cooking to complete
go func(f string) {
cook(f)
// call done when cooking completes
wg.Done()
}(food)
}
// wait
wg.Wait()
// time
fmt.Printf("took %.0f sec to cook\n", time.Since(since).Seconds())
}
// cook cook the food
func cook(food string) {
fmt.Printf("cooking %s\n", food)
time.Sleep(2 * time.Second)
}
/*
output:
took 2 second to cook
*/
package main
import (
"fmt"
"time"
)
func main() {
since := time.Now()
// cooking
foodList := []string{"mushroom pizza", "pasta", "kebab", "cake"}
for _, food := range foodList {
// use a simple coroutine (this will fail as we do not wait for cooking to complete
// we call the cook function wrapped in a function that we call using a coroutine
go func(f string) {
cook(f)
}(food)
// or just
// go cook(food)
// works as we call cook in a coroutine
}
// time
fmt.Printf("took %.0f sec to cook\n", time.Since(since).Seconds())
}
// cook cook the food
func cook(food string) {
fmt.Printf("cooking %s\n", food)
time.Sleep(2 * time.Second)
}
/*
output:
took 0 second to cook
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment