user1776041
user1776041

Reputation: 117

Creating multiple threads C++

Im writing a program that multiplies two matrices using a variable number of threads and then compares execution time for each run. The user specifies the maximum number of threads to use and then the program does the multiplication with 1 thread, again with 2, 3, 4....up to max_threads (we don't have to worry about max_threads being more than 8). So whats the best way to create the threads for each run? Here's my best shot in the dark.

EDIT: I have to use 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);
    }
}

The code for multiplyMatrices is below.

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);
}

Upvotes: 2

Views: 9903

Answers (2)

Brady
Brady

Reputation: 10357

The biggest problem I see with your code is how you're passing the data to the thread function. The data should be passed as a pointer. The following should work better:

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)
    {
       ...

Upvotes: 0

Denis Ermolin
Denis Ermolin

Reputation: 5546

It is C++ use std::thread + std::bind:

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)));
}

Upvotes: 4

Related Questions