All the answers I was able to find so far suggest calling omp_set_num_threads
. While it's a proper answer for most cases, it doesn't work for me. Internally, calling omp_set_num_threads
causes a creation of per-thread ICV (or modification, if current thread already has one), and the number of threads is stored there. This means that if there is a different thread, that starts a parallel region, it won't see our new value. So calling omp_set_num_threads != setting OMP_NUM_THREADS env variable.
Is there a way to change global ICV?
Side note - why would I want to to this: I'm working with a library spawns a worker thread for me, so I don't really control it's life-cycle.
Simplest example to reproduce:
export OMP_NUM_THREADS=3
#include <omp.h>
#include <iostream>
#include <thread>
void job() {
#pragma omp parallel
{
if (omp_get_thread_num() == 0) {
std::cout << "Num threads:" << omp_get_num_threads() << std::endl;
}
};
}
int main () {
omp_set_num_threads(2);
#pragma omp parallel
{
if (omp_get_thread_num() == 0) {
std::cout << "Num threads:" << omp_get_num_threads() << std::endl;
}
};
std::thread t(job);
t.join();
}
This produces
Num threads:2
Num threads:3