我目前正在尝试使用 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;
};
但我无法让乘法函数接受结构