0

我目前正在尝试使用 pthreads.h 编写一个用于多线程矩阵乘法的 C++ 程序。

我正在尝试按如下方式创建线程

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

然后创建执行我的乘法函数的线程,该函数的编码如下

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
    }

我的错误在于我的乘法函数。我正在尝试找到一种兼容的方式来为每个线程传递 x 和 y 坐标,因此它具体知道要计算哪个总和,但我不确定如何以 pthreads_create() 函数可接受的方式执行此操作.

更新:我知道我必须使用一个结构来完成这个

struct mult_args {
    int row;
    int col;
};

但我无法让乘法函数接受结构

4

1 回答 1

0

您将不得不修改您的multiply函数,以便它采用单个void*参数。为此,您需要创建一个结构来存储xypthread_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);
}

然后在您的乘法函数中,像这样重写它,采用一个void*参数,该参数将是multiply_params我们传入的指针pthread_create。您必须从中转换此参数,void*以便我们可以访问其字段。

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

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

    delete params; // avoid memory leak        
    // ...
}
于 2017-10-24T17:03:12.580 回答