Home > Software design >  Using pthreads to complete work in for loop
Using pthreads to complete work in for loop

Time:10-13

I have a 2D array I need to perform some work on. Currently, I have a single-thread design for my program and I want to move it into a multi-thread design using pthreads (OpenMP would be much easier, but that is not acceptable for this task unfortunately). Here's a sample of the code I have below with my pthread_create call within a for loop to create 4 threads. I need to subsequently run a for loop after the pthread_create loop is done. How can I run the for loop using multiple threads? Do I need to create and pass a function to pthread_create or can I simply have the for loop immediately after?

void main() {

    int Array[10][15];

    int numThreads = 4;

    pthread_t threadId[numThreads];

    initArray(A,20); //Initializes the array and fills with some random data

    for(i = 0; i<numThreads; i  ){

        pthread_create( &threadId[i], NULL); //Normally this would take an argument for some command I want to run concurrently, however, I want to run a for loop next concurrently using pthreads.

    }

}

CodePudding user response:

How can I run the for loop using multiple threads?

You can't, not in the same sense that auto-parallelization with OpenMP would do. If you want to split loop iterations among multiple threads without OpenMP or a similar tool, then you need to implement that manually.

Do I need to create and pass a function to pthread_create or can I simply have the for loop immediately after?

The pthread_create() function is not variadic. All arguments are required. And like any C function, pthread_create() is not contextual. Its behavior is not contingent on the structure of the code around a call to it. The thread created by a successful call to pthread_create() will perform the work defined by the specified function and argument to that function. So yes, you have to create a function.

And note, again, that it is on you to define the function(s) appropriately and to pass appropriate arguments so as to implement the division of work you want.

  • Related