Skip to content

Instantly share code, notes, and snippets.

@Zambito1
Created October 21, 2018 22:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zambito1/b4a8784268e8f9610f7b30a79b4104dc to your computer and use it in GitHub Desktop.
Save Zambito1/b4a8784268e8f9610f7b30a79b4104dc to your computer and use it in GitHub Desktop.
Concurrent Matrix Multiplication Go
package main
import (
"fmt"
"strings"
"sync"
)
func main() {
mtxA := [][]int {
{0, 0, 0, 0},
{0, 1, 2, 3},
{0, 2, 4, 6},
{0, 3, 6, 9},
}
mtxB := [][]int {
{0, 1, 2, 3},
{1, 2, 3, 4},
{2, 3, 4, 5},
{3, 4, 5, 6},
}
fmt.Printf("Matrix A \n%s", matrixToString(mtxA))
fmt.Println()
fmt.Printf("Matrix B \n%s", matrixToString(mtxB))
fmt.Println()
fmt.Printf("Multiplication of A and B \n%s", matrixToString(multiplyMatrices(mtxA, mtxB)))
}
func matrixToString(mtx [][]int) string {
var result strings.Builder
for _, row := range mtx {
for _, elem := range row {
fmt.Fprintf(&result, "%-4d", elem)
}
fmt.Fprintf(&result, "\n")
}
return result.String()
}
func multiplyMatrices(mtxA [][]int, mtxB [][]int) [][]int {
if len(mtxA) > 0 && len(mtxA[0]) != len(mtxB) {
panic("Invalid operation")
}
/* Allocate the memory needed for the resulting matrix*/
result := make([][]int, len(mtxA))
for i := range result {
result[i] = make([]int, len(mtxB[0]))
}
var wg sync.WaitGroup
for i := range mtxA {
wg.Add(1)
go func(i int) {
fmt.Printf("Goroutine %d starting.\n", i)
defer wg.Done()
for j := range mtxB[i] {
for k := range mtxB {
result[i][j] += mtxA[i][k] * mtxB[k][j]
}
fmt.Printf("Goroutine %d calculating element C[%d, %d]=%d.\n", i, i, j, result[i][j])
}
}(i)
}
wg.Wait()
fmt.Println()
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment