Skip to content

Instantly share code, notes, and snippets.

@hamadu
Created November 7, 2015 05:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hamadu/193959ef65a660bc1ce3 to your computer and use it in GitHub Desktop.
Save hamadu/193959ef65a660bc1ce3 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math/rand"
"os"
"strconv"
"runtime"
)
type Matrix [][]int
func computePart(i int, a, b, c *Matrix, ch chan int) {
ac := len((*a)[0])
bc := len((*b)[0])
for j := 0; j < bc; j++ {
part := 0
for k := 0; k < ac; k++ {
part += (*a)[i][k] * (*b)[k][j]
}
(*c)[i][j] = part
}
ch <- 1
}
func mulConcurrent(a, b *Matrix) Matrix {
ar := len(*a)
ac := len((*a)[0])
br := len(*b)
bc := len((*b)[0])
if ac != br {
panic("wrong matrix type")
}
c := make(Matrix, ar)
for i := 0 ; i < ar ; i++ {
c[i] = make([]int, bc)
}
ch := make(chan int)
for i := 0 ; i < ar ; i++ {
go computePart(i, a, b, &c, ch)
}
for i := 0 ; i < ar ; i++ {
<- ch
}
return c
}
func mul(a, b *Matrix) Matrix {
ar := len(*a)
ac := len((*a)[0])
br := len(*b)
bc := len((*b)[0])
if ac != br {
panic("wrong matrix type")
}
c := make(Matrix, ar)
for i := 0 ; i < ar ; i++ {
c[i] = make([]int, bc)
for j := 0 ; j < bc ; j++ {
for k := 0 ; k < ac ; k++ {
c[i][j] += (*a)[i][k] * (*b)[k][j]
}
}
}
return c
}
func main() {
n, _ := strconv.Atoi(os.Args[1])
k, _ := strconv.Atoi(os.Args[2])
runtime.GOMAXPROCS(k)
a := make(Matrix, n)
b := make(Matrix, n)
for i := 0 ; i < n ; i++ {
a[i] = make([]int, n)
b[i] = make([]int, n)
for j := 0 ; j < n ; j++ {
a[i][j] = rand.Intn(100)
b[i][j] = rand.Intn(100)
}
}
var c Matrix
if k == 0 {
c = mul(&a, &b)
} else {
c = mulConcurrent(&a, &b)
}
fmt.Println(c[0][0])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment