私はマルチスレッドの分野で全く新しいです。現時点では、同じサイズの2つの行列を乗算できるコマンドラインプログラムを実装しようとしています。主な目的は、ユーザーがコマンドライン引数として特定の数のスレッドを入力できることと、この数のスレッドを使用して乗算タスクを解決できることです。マトリクス特定のスレッド数での乗算
私のアプローチは、同様の課題解決しようとすると、次のJava実装に基づいています
:私は2つの問題を抱えている現時点で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);
}
}
:Java Implementation Matrix Multiplication Multi-Threading
私の現在の状態は、次のいずれかを
- 私の結果マトリックスには、有効な結果から遠い値が含まれています
- 私はしません自分のゴールに従って正しい方法で使用しているかどうかを知ってください。ユーザーは、使用するスレッドの数を指定できます。
誰かが私を解決策に導くことができれば非常に感謝します。
PS:私の似たような既存の投稿があることを知っていますが、投稿の主な課題は、ユーザーが行列の乗算を解決するスレッドの数を設定できるようにすることです。
'i'変数は、ループの存続期間全体を通して同じメモリ位置を参照します。この答えがあなたの問題を解決することを確認してください:http://stackoverflow.com/questions/34319303/thread-parameters-being-changed –
@HenkHolterman確かに、Parallel.For()は非常に快適なアプローチですが、特定の数のスレッドを定義する可能性があります。 – mian