Go is multithreaded by design! I was recently asked to add concurrent processing to a Go project. I used sync package which adds concurrency primitives support to the codebase.
Every Go program is executed by a "goroutine". Each goroutine can spawn more goroutines using the `go` keyword. Goroutines are multiplexed through a thread pool and cooperatively scheduled.
Here is a sample Go concurrent processing script:
package main import ( "fmt" "sync" ) func main() { slice := []string{"a", "b", "c", "d", "e"} sliceLength := len(slice) var wg sync.WaitGroup wg.Add(sliceLength) fmt.Println("Running for loop…") for i := 0; i < sliceLength; i++ { go func(i int) { defer wg.Done() val := slice[i] fmt.Printf("i: %v, val: %v\n", i, val) }(i) } wg.Wait() fmt.Println("Finished for loop") }