Reputation: 531
I have a question about possibility of implementing parallel execution inside a C program. My code looks like this:
struct str {
field;
field2;
struct name * ptrNext;
}
// something others
int main() {
struct str *pHead = malloc((...)sizeof(struct str));
struct str *ptr;
// other.....
/* Generation of dynamic list*/
ptr=pHead;
while(... ... ...) {
someFunctionOnNode(ptr);
ptr=ptr->ptrNext;
}
}
To increase the speed of program and to exploit having multiple cores in the processor, I would like to parallelize launch of function someFunctionOnNode
.
Is there a way to do this in C?
Upvotes: 3
Views: 8635
Reputation: 976
OpenMP is probably the best solution if the processors shear memory,if you have a cluster MPI. In OpenMP you just give pragmas to the compiler where you want to the code to run in parallel, so it is easy to adapt your existing code.
Upvotes: 0
Reputation: 74405
The simplest way to do that is to employ the OpenMP directives supported by virtually all modern C and C++ compilers. If your one is modern enough (i.e. supports OpenMP 3.0), then you could simply use tasks:
#pragma omp parallel
{
#pragma omp single
while(... ... ...) {
#pragma omp task
someFunctionOnNode(ptr); // This function call becomes a task
ptr=ptr->ptrNext;
}
#pragma omp taskwait
}
This single directive is so only one thread will walk the list and produce tasks, but otherwise all threads will pick a task to execute. The taskwait
directive waits for all tasks to finish. It is not strictly necessary since there is an implicit barrier synchronisation at the end of the parallel
region.
If your compiler does not support OpenMP 3.0, you can work around by putting all possible values of ptr
in a flat array and then performing parallel for loop over it:
datatype *ptrs[NUM_PTRS]; // Or allocate with new
int i = 0;
while (... ... ...) {
ptrs[i++] = ptr;
ptr = ptr->ptrNext;
}
#omp parallel for
for (i = 0; i < NUM_PTRS; i++)
{
someFunctionOnNode(ptrs[i]);
}
You should also enable OpenMP support but how it's done is compiler-specific.
Upvotes: 6
Reputation: 4934
Standard C does not have any parallel processing functionality. Your best bets are using platform dependent multi-threading functions or some other more portable mult-processing API.
Upvotes: 0
Reputation: 311
Launch each function in a separate thread. The threading API depends on what system you're developing on, but if it's UNIX-like check out pthreads:
https://computing.llnl.gov/tutorials/pthreads/
Upvotes: 0