0

現在、マルチスレッドの行列乗算のためのpthreads.hでC++プログラムを作成しようとしています。pthreadsマルチスレッドの行列乗算

私は

void *multiply(int x, int y) 
{ 
    int oldprod = 0, prod = 0, sum = 0; 
    cout << "multiply"; 

    for(int i = 0; i < rsize2; i++)//For each row in #ofrows in matrix 2 
    { 
     prod = matrix[x][i] * matrix2[i][y];//calculates the product 
     sum = oldprod + prod; //Running sum starting at 0 + first product 
     oldprod = prod; //Updates old product 
    } 

私のエラーは私の乗算機能であるが、以下のようにコーディングされている私の乗算機能を実行するスレッドを作成し、その後

int numthreads = (matrix[0].size() * rsize2);//Calculates # of threads needed 
pthread_t *threads; 
threads = (pthread_t*)malloc(numthreads * sizeof(pthread_t));//Allocates memory for threads 
int rc; 
for (int mult = 0; mult < numthreads; mult++)//rsize2 
{ 
    struct mult_args args; 
    args.row = mult; 
    args.col = mult; 
    cout << "Creating thread # " << mult; 
    cout << endl; 
    rc = pthread_create(&threads[mult], 0, multiply(&args), 0); 
} 

これを次のようにスレッドを作成しようとしています。私は互換性のある方法を各スレッドのxとy座標を渡すようにしようとしているので、計算する集計は具体的に分かっていますが、pthreads_create()関数で受け入れられる方法でこれを行う方法がわかりません。

更新: は私がこの

struct mult_args { 
    int row; 
    int col; 
}; 

を達成するために構造体を使用する必要がありますが、私は構造体

+0

第1位で 'std :: thread'を使用しないのはなぜですか? – user0042

+0

プロジェクトのためのpthreadsが必要です – Zac

+0

_pthreadsはproject_YAITのための要件です(さらに別の無能な先生) –

答えて

0

を受け入れるように乗算関数を得ることができないあなたは、あなたのmultiplyを変更する必要がありますことを知っています1つのvoid*パラメータが必要です。これを行うには、構造体を作成してxyを作成し、ポインタをpthread_createに渡す必要があります。

struct multiply_params 
{ 
    int x; 
    int y; 

    multiply_params(int x_arg, int y_arg) noexcept : 
     x(x_arg), y(y_arg) 
    {} 
}; 

// ... 

for (int mult = 0; mult < numthreads; mult++) 
{ 
    cout << "Creating thread # " << mult; 
    cout << endl; 

    multiply_params* params = new multiply_params(1, 0); 
    rc = pthread_create(&threads[mult], 0, multiply, (void*) params); 
} 

は、その後、あなたの乗算機能では、我々は pthread_createに渡さ multiply_paramsのポインタになります単一 void*パラメータを取って、このようにそれを書き換えます。あなたはフィールドにアクセスできるように、この引数を void*からキャストする必要があります。

void* multiply(void* arg) 
{ 
    multiply_params* params = (multiply_params*) arg; 

    int x = params->x; 
    int y = params->y; 

    delete params; // avoid memory leak   
    // ... 
}