0

I'm currently trying to write a C++ program with pthreads.h for multi-threaded matrix multiplication.

I'm trying to create the threads as follows

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

This then creates threads that execute my multiply function which is coded as follows

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
    }

My error lies in my multiply function. I'm trying to find a compatible way to pass in an x and y coordinate for each thread so it knows specifically which summation to calculate but i'm not sure how to do this in a way that is acceptable for the pthreads_create() function.

Update: I know that I have to use a struct to accomplish this

struct mult_args {
    int row;
    int col;
};

but I can't get the multiply function to accept the struct

Zac
  • 109
  • 1
  • 1
  • 8

1 Answers1

0

You will have to modify your multiply function so that it takes a single void* parameter. To do this, you will need to make a struct to store x and y and pass a pointer to it in 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);
}

Then in your multiply function, rewrite it like this, taking a single void* parameter which will be the pointer of multiply_params which we passed into pthread_create. You have to cast this argument from void* so we can access its fields.

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

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

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