I am writing a program in c++ in visual studio to be able to handle a line at a park. I have all of my customers in a line at the park and I want to be able to service them using multithreading with openmp.
When I put the pragma and such in, I have multiple threads servicing the same customer at the same time for each and every customer I create, not what I want.
I want for example, if I had two threads and four customers, that thread one to do customer one while thread 2 does customer 2. Then I would like thread 1 to do customer 3 and thread 2 customer 4 at the same time. I don't know if its possible or if there is a better way, but I need to use openMP.
You can associate each for iteration as a customer and assign them (costumer) to threads in a static manner.
#pragma omp parallel for schedule(static, CHUNKSIZE)
for(i = 0; i < customer_max; i++)
{
// do something with customers
}
static: In this distribution threads have their work statically precalculated before the execution of the actual loop. The iterations are divided among threads equally by default. However, if you specify an integer for the parameter CHUNKSIZE
the distribution will allocate chunks of size CHUNKSIZE
of contiguous iterations to threads.
In your example with 2 threads and 4 customers, you would use CHUNKSIZE = 1. Thus, the thread 0 will execute both costumer 0 and 2, while thread 2 would execute costumer 1 and 3.
If you do not specify the CHUNKSIZE
, thread 0 would execute the first 2 customers and the thread 1 the remaining 2.
In another hand, if you prefer that each thread serve the customers in a dynamic manner you can use a dynamic distribution.
#pragma omp parallel for schedule(dynamic)
for(i = 0; i < customer_max; i++)
{
// do something with customers
}
The dynamic schedule is appropriate for the case of a for with iterations that perform work that time-wise can vary a lot. Analogously in your case, If you have consumers who take different times to be served.