The maximum number of threads in C++ OpenMP is always 1
We set the task to write a couple of algorithms in C++ using OpenMP. Since I have a Macbook, I had to install the Clion IDE and work with it.
Code main.cpp:
#include <iostream>
#include "/usr/local/opt/libomp/include/omp.h"
#define THREAD_NUM 4
int main()
{
omp_set_num_threads(THREAD_NUM);
std::cout << omp_get_thread_limit << std::endl;
#pragma omp parallel for num_threads(4)
{
std::cout << "Number of available threads: " << omp_get_num_threads() << std::endl;
std::cout << "Current thread number: " << omp_get_thread_num() << std::endl;
std::cout << "Hello, World!" << std::endl;
}
return 0;
}
Code CMakeLists.txt:
cmake_minimum_required(VERSION 3.14)
project(OpenMPTest)
set(CMAKE_CXX_STANDARD 17)
add_executable(OpenMPTest main.cpp)
find_package(OpenMP REQUIRED)
target_link_libraries(${PROJECT_NAME} ${OpenMP_CXX_LIBRARIES})
When compiling, it always outputs the following:
1
Number of available threads: 1
Current thread number: 0
Hello, World!
I can't understand the reason why the number of threads doesn't increase according to the value I'm trying to set it. I must say that I have not worked with C++ or C ++ before. OpenMP.
OS: macOS Catalina Beta Version 10.15.6 (19G36e)
1 answers
You use the omp parallel for
directive, but you don't have a for
loop there. What do you expect to get like this? Remove the word for
from here and you will be happy.
#include <iostream>
#include "/usr/local/opt/libomp/include/omp.h"
// #include <omp.h>
#define THREAD_NUM 4
int main()
{
omp_set_num_threads(THREAD_NUM);
std::cout << omp_get_thread_limit() << std::endl;
#pragma omp parallel num_threads(4)
{
std::cout << "Number of available threads: " << omp_get_num_threads() << std::endl;
std::cout << "Current thread number: " << omp_get_thread_num() << std::endl;
std::cout << "Hello, World!" << std::endl;
}
return 0;
}
The example was built using mingw-w64
under Win10; command line: g++ test2.cpp -o test2 -O2 -fopenmp
PS: also, you didn't write parentheses for the function omp_get_thread_limit()
and because of this, you didn't get the corresponding number.