Go threads are parallel


Over the weekend, I installed Ubuntu on my idle 2007 8-core Mac Pro.

To warm it up, I wrote this little test program to see if it would get all eight cores working at once.

It did.


package main
    
import (
        "sync"
        "golang.org/x/crypto/bcrypt"
)

// this was just something that would take a little time to run
func trial() {
        password := []byte("Hello, world")

        // Hashing the password with the default cost of 10
        hashedPassword, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
        if err != nil {
                panic(err)
        }
        // Comparing the password with the hash
        err = bcrypt.CompareHashAndPassword(hashedPassword, password)
        if err != nil {
                panic(err)
        }
}

func main() {
        // Vary this to increase or decrease the amount of parallelism.
        // Numbers up to 8 seem to map goroutines to cores (on my 8-core machine).
        threads := 30
        max := 10
        var wg sync.WaitGroup
        wg.Add(threads)
        for t := 0; t < threads; t++ {
                go func() {
                        for i := 0; i < max; i++ {
                                trial()
                        }
                        wg.Done()
                }()
        }
        wg.Wait()
}