【发布时间】:2016-04-17 13:43:07
【问题描述】:
我是多线程领域的新手。目前我正在尝试实现一个命令行程序,它能够将两个大小相等的矩阵相乘。主要目标是用户可以输入特定数量的线程作为命令行参数,并使用这个数量的线程来解决乘法任务。
我的方法基于以下尝试解决类似任务的 java 实现:Java Implementation Matrix Multiplication Multi-Threading
我目前的状态如下:
using System;
using System.Threading;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
class Program
{
static int rows = 16;
static int columns = 16;
static int[] temp = new int[rows*columns];
static int[,] matrixA = new int[rows, columns];
static int[,] matrixB = new int[rows, columns];
static int[,] result = new int[rows, columns];
static Thread[] threadPool;
static void runMultiplication(int index){
for(int i = 0; i < rows; i++){
for(int j = 0; j < columns; j++){
Console.WriteLine();
result[index, i] += matrixA[index, j] * matrixB[j, i];
}
}
}
static void fillMatrix(){
for (int i = 0; i < matrixA.GetLength(0); i++) {
for (int j = 0; j < matrixA.GetLength(1); j++) {
matrixA[i, j] = 1;
matrixB[i, j] = 2;
}
}
}
static void multiplyMatrices(){
threadPool = new Thread[rows];
for(int i = 0; i < rows; i++){
threadPool[i] = new Thread(() => runMultiplication(i));
threadPool[i].Start();
}
for(int i = 0; i < rows; i++){
try{
threadPool[i].Join();
}catch (Exception e){
Console.WriteLine(e.Message);
}
}
}
static void printMatrix(int[,] matrix) {
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
Console.Write(string.Format("{0} ", matrix[i, j]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
}
static void Main(String[] args){
fillMatrix();
multiplyMatrices();
printMatrix(result);
}
}
目前我有两个问题:
- 我的结果矩阵包含远离有效结果的值
- 根据我的目标,我不知道我是否走在正确的道路上,即用户可以指定应该使用多少线程。
如果有人能指导我找到解决方案,我将不胜感激。
PS:我知道现有的帖子与我的类似,但我帖子中的主要挑战是允许用户设置线程数,然后解决矩阵乘法问题。
【问题讨论】:
-
i变量在循环的整个生命周期中引用相同的内存位置。检查此答案将解决您的问题:stackoverflow.com/questions/34319303/… -
@HenkHolterman 确实,Parallel.For() 将是一种非常舒适的方法,但我不得不为用户提供定义特定线程数的可能性。
标签: c# multithreading matrix