Last active
July 17, 2023 02:29
-
-
Save slcjordan/e05de3ab485321ff6cbd to your computer and use it in GitHub Desktop.
Example concurrent matrix multiplication using actors pattern in go.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math/rand" | |
) | |
// A Matrix is a square 6*6 of type int. | |
type Matrix [6][6]int | |
func (m *Matrix) String() string { | |
result := "" | |
for j := 0; j < 6; j++ { | |
result = result + fmt.Sprintf("%v\n", m[j]) | |
} | |
return result | |
} | |
// Random generates a random matrix. | |
func Random() *Matrix { | |
content := [6][6]int{} | |
for i := 0; i < 36; i++ { | |
content[i/6][i%6] = rand.Int() | |
} | |
result := Matrix(content) | |
return &result | |
} | |
// Product is the result of matrix multiplications. | |
var Product = Random() | |
func actor(transforms <-chan *Matrix, rowNum int) { | |
for multiplier := range transforms { | |
row := [6]int{} | |
for j := 0; j < 6; j++ { | |
running := 0 | |
for k := 0; k < 6; k++ { | |
running = running + Product[rowNum][k]*multiplier[k][j] | |
} | |
row[j] = running | |
} | |
Product[rowNum] = row | |
} | |
} | |
func runActors(transforms <-chan *Matrix) { | |
inputs := [6]chan *Matrix{} | |
for i := 0; i < 6; i++ { | |
inputs[i] = make(chan *Matrix) | |
go actor(inputs[i], i) | |
defer close(inputs[i]) | |
} | |
for x := range transforms { | |
for _, in := range inputs { | |
in <- x | |
} | |
} | |
} | |
func main() { | |
transforms := make(chan *Matrix) | |
go runActors(transforms) | |
for i := 0; i < 1000; i++ { | |
transforms <- Random() | |
} | |
close(transforms) | |
fmt.Println(Product) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment