I am following an example to implement threads in C: http://ramcdougal.com/threads.html.
This example is using a 1-dimensional array. I need a dynamic 2 dimensional array.
What would it look like if in the main() it was int **array instead of int array[ARRAYSIZE]?
My problem is how to pass a pointer to a 2-dimensional array to the struct.
The idea is, that I have a big array, and each thread should only fill a certain area of that array.
Thanks a lot !
Here’s the code from the example:
struct ThreadData {
int start, stop;
int* array;
};
void* squarer(struct ThreadData* td) {
struct ThreadData* data=(struct ThreadData*) td;
int start=data->start;
int stop=data->stop;
int* array=data->array;
int i;
for (i=start; i<stop; i++) {
array[i]=i*i;
}
return NULL;
}
int main(void) {
int array[ARRAYSIZE];
pthread_t thread[NUMTHREADS];
struct ThreadData data[NUMTHREADS];
int i;
int tasksPerThread=(ARRAYSIZE+NUMTHREADS-1)/NUMTHREADS;
for (i=0; i<NUMTHREADS; i++) {
data[i].start=i*tasksPerThread;
data[i].stop=(i+1)*tasksPerThread;
data[i].array=array;
}
/* the last thread must not go past the end of the array */
data[NUMTHREADS-1].stop=ARRAYSIZE;
/* Launch Threads */
for (i=0; i<NUMTHREADS; i++) {
pthread_create(&thread[i], NULL, squarer, &data[i]);
}
/* Wait for Threads to Finish */
for (i=0; i<NUMTHREADS; i++) {
pthread_join(thread[i], NULL);
}
/* Display Result */
for (i=0; i<ARRAYSIZE; i++) {
printf("%d ", array[i]);
}
printf("\n");
return 0;
}
Think of it this way:
When working with a one dimensional array,
startandstopare one dimensional vectors representing coordinates in 1-D space (And a 1-D vector can be represented with an integer, which is what the original code uses.)So in a 2-D array,
startandstopought to be 2-D vectors:Then, you split rectangular blocks amongst the threads. And each thread gets the position of the top left corner of its block in
start, and the position of the bottom right corner of its block instop.Remember that the blocks, being rectangular, can be tall strips (1 column per thread), or long (one row per thread), or square, or anywhere in between. You have to decide which shape works faster, by benchmarking.
In a sense,
tasksPerThreadalso has two dimensions. With the actual number of tasks becomingtasksPerThread[0] * tasksPerThread[1].