I want to use OpenMP
to attain this effect: fix the number of threads, if there is an idle thread, dispatch the task into it, else wait for an idle one. The following is my test code:
#include <omp.h>
#include <stdio.h>
#include <unistd.h>
void func(void) {
#pragma omp parallel for
for (int i = 0; i < 3; i++)
{
sleep(30);
printf("%d\n", omp_get_thread_num());
}
}
int main(void) {
omp_set_nested(1);
omp_set_num_threads(omp_get_num_procs());
#pragma omp parallel for
for (int i = 0; i < 8; i++)
{
printf("%d\n", omp_get_thread_num());
func();
}
return 0;
}
Actually, my machine contains 24
cores, so
omp_set_num_threads(omp_get_num_procs())
will launch 24
threads at the beginning. Then main
's for-loop
will occupy 8
threads, during every thread, a func
will be called, therefore additonal 2
threads ought to be used. From my calculation, I think 24
threads will be enough. But in actual running, there are totally 208
threads generated.
So my questions are as follows:
(1) Why so many threads are created though 24
seems enough?
(2) Is it possible to fix the number of threads (E.g., same as the number of cores) and dispatch the task when there is idle one?