Hi experts,
I'm a newbie to golang. One of my first ideas to use goroutine is to write a matrix multiplying programme: C = A*B. I though the calculating of every element of C: c[i][j] = row i of A * column j of B could be run by a goroutine. This is the skeleton of the code:
t1 := time.Now().UnixNano() //benchmark
rand.Seed(t1)
for i := 0; i < n; i++ {
ai,_ := get_row(a,i)
for j := 0; j < t; j ++ {
bj, _ := get_column(b,j)
// c[i][j],_ = dot_product(ai, bj)
go func(element *int, ai,bj []int) {
*element,_ = dot_product(ai,bj)
wg.Done()
}(&c[i][j], ai, bj)
}
}
wg.Wait() // waiting for all the elements have been calculated
t2 := time.Now().UnixNano()
fmt.Printf("the dot_product using goroutine costs %v\n", t2 - t1)
As the goroutines will run "concurrently" on my laptop with 8 CPU cores to calculate the element of matrix, I thought the code would ran faster than not using goroutine. In fact, it ran slowlier than not using goroutine. Any explanation of this? By the way, the dimension of matrix is 100x100.
Best regards,
Yuwen