Hi Guys,
I have a question on using Grand Central Dispatch.
I am using GCD to parallelize a for loop. However, I am summing up the result from each iteration of the for loop. The summing up portion is the critical section. I can succesfully parallelize the for loop using dispatch_apply. But, I am unable to figure out how to correctly implement the critical section. Below is the baseline code and GCD based code. Can you help?
Base code:
for (i=0;i<= num_steps; i++)
{
x = (i+0.5)*step;
sum = sum + 4.0/(1.0+x*x);
}
pi = step * sum;
printf("The value of pi is %f\n", pi);
Code written Using GCD:
dispatch_queue_t theQueue = dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_apply (num_steps, theQueue, ^ (size_t i)
{
double x, pi, sum = 0.0;
step = 1.0/(double) num_steps;
x = (i+0.5)*step;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),
^{
double sum;
sum = sum + 4.0/(1.0+x*x);
});
pi = step * sum;
printf("The value of pi is %f\n", pi);
});
Thanks a bunch.
Regards,
Hema
I have a question on using Grand Central Dispatch.
I am using GCD to parallelize a for loop. However, I am summing up the result from each iteration of the for loop. The summing up portion is the critical section. I can succesfully parallelize the for loop using dispatch_apply. But, I am unable to figure out how to correctly implement the critical section. Below is the baseline code and GCD based code. Can you help?
Base code:
for (i=0;i<= num_steps; i++)
{
x = (i+0.5)*step;
sum = sum + 4.0/(1.0+x*x);
}
pi = step * sum;
printf("The value of pi is %f\n", pi);
Code written Using GCD:
dispatch_queue_t theQueue = dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_apply (num_steps, theQueue, ^ (size_t i)
{
double x, pi, sum = 0.0;
step = 1.0/(double) num_steps;
x = (i+0.5)*step;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),
^{
double sum;
sum = sum + 4.0/(1.0+x*x);
});
pi = step * sum;
printf("The value of pi is %f\n", pi);
});
Thanks a bunch.
Regards,
Hema