Multithreading 二维矩阵的线与和
我必须计算二维矩阵中元素的和,使用单独的线程来计算每行的和。然后主线程将这些总和相加,打印出最终结果。 你们能看到怎么了吗? (我对线程的东西都是新手)Multithreading 二维矩阵的线与和,multithreading,matrix,terminal,sum,row,Multithreading,Matrix,Terminal,Sum,Row,我必须计算二维矩阵中元素的和,使用单独的线程来计算每行的和。然后主线程将这些总和相加,打印出最终结果。 你们能看到怎么了吗? (我对线程的东西都是新手) #包括 #包括 无效总和(无效*_a,整数m,整数n,整数和) { int i; int(*a)[m]=\u a; 对于(i=1;i我看到的一个问题是,您的循环基本上是这样做的: for each row start thread add thread's sum to total wait for thread to
#包括
#包括
无效总和(无效*_a,整数m,整数n,整数和)
{
int i;
int(*a)[m]=\u a;
对于(i=1;i我看到的一个问题是,您的循环基本上是这样做的:
for each row
start thread
add thread's sum to total
wait for thread to exit
这是行不通的,因为您要在线程完成计算之前添加线程的总和。您需要等待线程完成:
start thread
wait for thread to exit
add thread's sum to total
但是,该模型没有利用多个线程,一次只能运行一个线程
您需要做的是创建所有线程并将它们存储在数组中。然后等待每个线程退出并将其总和添加到总数中。类似于:
for i = 0 to num_threads-1
threads[i] = pthread_create(&threads[i], NULL, &sums[i], ...)
然后
for i = 0 to num_threads-1
pthread_join(&threads[i], ...);
sum += sums[i];
这样,所有线程都在同一时间运行,并且只有在线程完成后才能获取结果
for i = 0 to num_threads-1
pthread_join(&threads[i], ...);
sum += sums[i];