C语言 如何让 C 中的多个线程处理二维数组的同一个 for 循环?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13422394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can i have multiple threads in C working on the same for loop of a two-dimensional array?
提问by programmer
i have a program in C.
我有一个 C 程序。
I have created 3 threads with pthread_create and i have created a mutex in order to lock/unlock the critical regions.
我使用 pthread_create 创建了 3 个线程,并且我创建了一个互斥锁以锁定/解锁关键区域。
The 3nd argumentof pthread_createis a pointer to a function that the thread will execute.
该3ND参数的在pthread_create是一个指向该线程将执行的功能。
In the examples i've found in the Web, this function is always very simplee.g. prints the thread id or prints a message.
在我在网上找到的例子中,这个函数 总是非常简单,例如打印线程 ID 或打印一条消息。
What happens when the function that the thread shall execute contains a for loop?
当线程要执行的函数包含for 循环时会发生什么?
Cause in my program i would like each one of the threads to work with a two dimensional array.
因为在我的程序中,我希望每个线程都使用二维数组。
Each thread shall find the sum of a line of a two-dimensional array. e.g.
每个线程应找到二维数组的一行的总和。例如
Thread1shall calculate the sum of first line of the 2-dimensional array
Thread1计算二维数组第一行的总和
Thread2shall calculate the sum of the second line
Thread1shall calculate the sum of the 3nd line
Thread3shall calculate the sum of the 3nd line
线程2将计算的第二行的总和
线程1将计算3ND线的总和
Thread3应计算3ND线的总和
I don't care about the order of the threads, but i need every thread to pick one of the lines.
我不关心线程的顺序,但我需要每个线程都选择其中一行。
I have the following code that sumstwo cells in the two dimensional array.
我有以下代码对二维数组中的两个单元格求和。
The program:
该程序:
creates NTHREADS
for(i=0; i < NTHREADS; i++) { pthread_create( &thread_id[i], NULL, CalculateSum, NULL ); }Each thread waits for the others to finish
for(j=0; j < NTHREADS; j++) { pthread_join( thread_id[j], NULL); }the function that each thread shall execute but for ONE lineof the array and NOTfor the WHOLE array is
void *CalculateSum(void *dummyPtr) { pthread_mutex_lock( &mutex1 ); int i,j,sum = 0; for( i = 0; i <= N-1; i++) { for( j = 0; j <= M-1; j++) { sum = dimensional_array[i][j] + dimensional_array[i][j]; } printf(" Sum = %d\n", sum); } counter++; pthread_mutex_unlock( &mutex1 ); }
创建 NTHREADS
for(i=0; i < NTHREADS; i++) { pthread_create( &thread_id[i], NULL, CalculateSum, NULL ); }每个线程等待其他线程完成
for(j=0; j < NTHREADS; j++) { pthread_join( thread_id[j], NULL); }每个线程应执行但对于数组的一行而不是对于整个数组的函数是
void *CalculateSum(void *dummyPtr) { pthread_mutex_lock( &mutex1 ); int i,j,sum = 0; for( i = 0; i <= N-1; i++) { for( j = 0; j <= M-1; j++) { sum = dimensional_array[i][j] + dimensional_array[i][j]; } printf(" Sum = %d\n", sum); } counter++; pthread_mutex_unlock( &mutex1 ); }
The whole program is as follows: The program does not have any compilation error.
整个程序如下: 程序没有任何编译错误。
In order to run it you shall do: gcc -pthread program.c
为了运行它,你应该这样做:gcc -pthread program.c
//program.c
#include <stdio.h>
#include <pthread.h>
#define NTHREADS 3
void *CalculateSum(void *);
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int counter = 0;
#define N 10
#define M 10
int dimensional_array[N][M];
main()
{
pthread_t thread_id[NTHREADS];
int i, j;
for (i = 0; i <= N - 1; i++ )
for( j = 0; j <= M - 1; j++)
dimensional_array[i][j] = i;
for(i=0; i < NTHREADS; i++)
{
pthread_create( &thread_id[i], NULL, CalculateSum, NULL );
}
for(j=0; j < NTHREADS; j++)
{
pthread_join( thread_id[j], NULL);
}
printf("Final counter value: %d\n", counter);
//print ARRAY
for (i = 0; i <= N-1; i++ ) {
for( j = 0; j <= M-1; j++)
printf("%d\t",dimensional_array[i][j]);
printf("\n");
}
}
//Calculate
void *CalculateSum(void *dummyPtr)
{
pthread_mutex_lock( &mutex1 );
int i,j,sum = 0;
for( i = 0; i <= N-1; i++) {
for( j = 0; j <= M-1; j++) {
sum = dimensional_array[i][j] + dimensional_array[i][j];
}
printf(" Sum = %d\n", sum);
}
counter++;
pthread_mutex_unlock( &mutex1 );
}
So, i would like each thread to find the sum of a line but i'm confused, i don't know how to do that.
所以,我希望每个线程都能找到一行的总和,但我很困惑,我不知道该怎么做。
In my program every time a thread calls the Calculate function, all the sum of the lines are computed and not just one
在我的程序中,每次线程调用计算函数时,都会计算所有行的总和,而不仅仅是一个
[Caution:For simplicity i sum the first element with it's own,the point is to understand how those threads can all take place in that for loop]
[注意:为简单起见,我将第一个元素与它自己的元素相加,重点是了解这些线程如何在该 for 循环中发生]
I would be glad if someone could help me
如果有人可以帮助我,我会很高兴
Thanks, in advance
提前致谢
回答by dasblinkenlight
You should create an array of per-thread parameters, and pass these to the threads one-by-one. In your case a single pointer to intis sufficient: you pass to the thread its index threadindexfrom zero to NTHREADS, and the thread passes back the sum for rows such that row % NTHREADS == threadindex.
您应该创建一个每个线程参数的数组,并将这些参数一个一个地传递给线程。在您的情况下,单个指针int就足够了:您将其索引threadindex从零传递给线程NTHREADS,并且线程将行的总和传回,使得row % NTHREADS == threadindex.
Here is how your thread function looks:
这是您的线程函数的外观:
void *CalculateSum(void *args)
{
int *argPtr = args;
int i,j,sum = 0;
int threadindex = *argPtr;
for( i = 0; i <= N-1; i++) {
if (i % NTHREADS != threadindex) continue;
for( j = 0; j <= M-1; j++) {
sum += dimensional_array[i][j];
}
}
pthread_mutex_lock( &mutex1 ); Mutex must go here
counter++;
pthread_mutex_unlock( &mutex1 );
// Pass the value back:
*argPtr = sum;
}
main()
{
pthread_t thread_id[NTHREADS];
int thread_args[NTHREADS];
int i, j;
pthread_mutex_init(&mutex1, NULL);
for (i = 0; i <= N - 1; i++ )
for( j = 0; j <= M - 1; j++)
dimensional_array[i][j] = i;
for(i=0; i < NTHREADS; i++)
{
thread_args[i] = i;
pthread_create( &thread_id[i], NULL, CalculateSum, &thread_args[i]);
}
int sum = 0;
for(j=0; j < NTHREADS; j++)
{
pthread_join( thread_id[j], NULL);
sum += thread_args[i];
}
printf("Final counter value: %d. Total: %d\n", counter, sum);
}
回答by Johnny Mopp
To calc the sum of one line (ignoring the thread stuff):
计算一行的总和(忽略线程内容):
void *CalculateSum(void *dummyPtr)
{
int j,sum = 0;
int i = (int)dummyPtr;
for( j = 0; j <= M-1; j++) {
sum += dimensional_array[i][j];
}
printf(" Sum = %d\n", sum);
pthread_mutex_lock( &mutex1 );
counter++;
pthread_mutex_unlock( &mutex1 );
}
And then create the thread like this:
然后像这样创建线程:
int line_number = 2; // Or whatever line to print`enter code here`
pthread_create( &thread_id[i], NULL, CalculateSum, (void *)line_number );
EDIT: put "counter++" back in.
编辑:把“counter++”放回去。

