Reputation: 5659
I want to do multi threading in one of my for loop
using #pragma omp parallel
. So, i am writing the following code:
#pragma omp parallel for
for(int i=0; i<square->total; i++)
{
......
}
My project have a CMakeList.txt and Makefile. I don't understand, how do i tell the compiler and linker to use openMP?
Updates:
I have edited my CMakeList.txt
with following code
find_package(OpenMP)
if (OPENMP_FOUND)
set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}")
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
endif()
and then i did cmake ..
and got the following result at terminal:
-- The C compiler identification is GNU
-- The CXX compiler identification is GNU
-- Check for working C compiler: /usr/bin/gcc
-- Check for working C compiler: /usr/bin/gcc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Try OpenMP C flag = [-fopenmp]
-- Performing Test OpenMP_FLAG_DETECTED
-- Performing Test OpenMP_FLAG_DETECTED - Success
-- Try OpenMP CXX flag = [-fopenmp]
-- Performing Test OpenMP_FLAG_DETECTED
-- Performing Test OpenMP_FLAG_DETECTED - Success
-- Found OpenMP: -fopenmp
-- Configuring done
-- Generating done
Upvotes: 0
Views: 3361
Reputation: 10852
@user2440724
I wrote the code sample as you ask:
#include <string>
#include <iostream>
#include <vector>
#include <omp.h>
using namespace std;
using namespace cv;
//----------------------------------------------------------
// MAIN
//----------------------------------------------------------
int main(int argc, char* argv[])
{
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (int i = 0; i < 10; i++)
{
std::cout << "A" << std::endl;
}
getchar();
return 0;
}
in vs2010 you need enable openmp as shown below:
Good tutorial for linux here: http://goulassoup.wordpress.com/2011/10/28/openmp-tutorial/ And GNU OpenMP docs: http://gcc.gnu.org/onlinedocs/libgomp/index.html#toc_Top
Upvotes: 1
Reputation: 8677
The #pragma ...
should be on its own line.
#pragma omp parallel for
for(int i=0; i<square->total; i++)
{
......
}
Make sure you don't forget the for
at the end of the #pragma
.
First make sure it works with the #pragma
line commented out, then adding the line should be fine (assuming everything inside the loop is OK to parallelize, no concurrency issues or whatnot).
Also make sure you pass -fopenmp
to both the compiler and the linker, and you have #include <omp.h>
at the top.
Upvotes: 2