2

可変数のスレッドを使用して2つの行列を乗算し、実行ごとに実行時間を比較するプログラムを作成しています。ユーザーが使用するスレッドの最大数を指定すると、プログラムは1スレッド、2、3、4 ....最大max_threadsで乗算を実行します(max_threadsが8を超えることを心配する必要はありません)。 。では、実行ごとにスレッドを作成するための最良の方法は何ですか?これが暗闇の中での私のベストショットです。

編集:pthreadを使用する必要があります。

//Ive already called multiplyMatrices for the single thread run. Start with 2 threads.
for (int h=2; h <= max_threads; h++)
{
    for(int i = 0; i < h; i++)
    {   
        pthread_create(thr_id[i],NULL, multiplyMatrices, i);
    }

    for(int i = 0; i < h; i++)
    {
        pthread_join(thr_id[i],NULL);
    }
}

multiplyMatricesのコードは以下のとおりです。

void* multiplyMatrices(void* val)
{    
    for(int i = 0; i < n; i = i*val)
    {
        for(int j = 0; j < p; j++)
    {
            c[i][j] = 0;
            for(int k = 0; k < m; k++)
        {
                c[i][j] += matrix_A[i][k] * matrix_B[k][j];
            }
        }
    val++;
    }
    pthread_exit(0);
}
4

2 に答える 2

4

std :: thread + std :: bind:をC++使用します。

std::vector<std::thread > thread_pool;
thread_pool.reserve(h);
void* someData;
for(int i = 0; i < h; i++)
{   
    thread_pool.push_back(std::thread(std::bind(multiplyMatrices, someData)));
}
于 2012-11-01T08:04:13.937 に答える
0

あなたのコードで私が目にする最大の問題は、データをスレッド関数に渡す方法です。データはポインターとして渡す必要があります。以下はより適切に機能するはずです。

for (int h=2; h <= max_threads; h++)
{
    for(int i = 0; i < h; i++)
    {   
        // Notice Im passing a pointer to i here.
        // Since i may go out of scope, and its value could change before the
        // thread is started and multiplyMatrices() is called, this could be
        // risky. Consider using an array/vector defined before these for
        // loops to avoid this problem.
        pthread_create(thr_id[i],NULL, multiplyMatrices, &i);
        ...

void* multiplyMatrices(void* valPtr)
{    
    int val = *((int*) valPtr);
    for(int i = 0; i < n; i = i*val)
    {
       ...
于 2012-11-01T13:08:07.977 に答える