OpenMP是目前被广泛接受的,用于共享内存并行系统的多处理器程序设计的一套指导性的编译处理方案。它提供了对并行算法的高层的抽象描述,程序员通过在源代码中加入专用的pragma来指明自己的意图,由此编译器可以自动将程序进行并行化,并在必要之处加入同步互斥以及通信。在Windows下利用Visual Studio来开发基于OpenMP的并发程序已有很多现成的资料可查,本文主要来讨论在OS X系统上利用GCC来开发基于OpenMP之并发程序的基本方法。
在前面的文章《OS X上安装Homebrew和GCC的图文攻略》里,我们已经在OS X上搭建了一个GCC的开发环境。注意新版的Xcode已经不再支持OpenMP,因此你仍然需要安装并配置一个纯GCC的环境,而非用苹果的clang来进行映射。
打开Terminal,然后新建一个子目录来存放即将要编辑的程序源文件,再用nano新建一个新的CPP文件:
> mkdir omp_test
> cd omp_test
> nano omp_test.cpp
然后在nano中编辑如下所示之示例代码:
#include
#include
#include
#include
int main( int argc, char* argv[] )
{
omp_set_num_threads( 8 );
double pi = acos( -1.0 );
std::cout << "Allocating memory ..." << std::endl;
std::vector<double> my_vector( 128000000, 0.0 );
std::cout << "Done!" << std::endl << std::endl;
std::cout << "Entering main loop ... " << std::endl;
#pragma omp parallel for
for( int i=0; i < my_vector.size(); i++ )
{
my_vector[i] = exp( -sin( i*i + pi*log(i+1) ) );
}
std::cout << "Done!" << std::endl;
return 0;
}
nano是Unix和类Unix系统中的一个文本编辑器,我们这里不打算详细讨论它的使用方法,你可以查阅相关资料以了解更多。
当然你也完全可以在拥有GUI的Sublime Text下来编辑你的源代码,我们这里仅仅是要让大家体验一下在命令行模式下开发的感觉。
接下来我们就来编辑Makefile文件,请在Terminal上使用下面命令:
> nano Makefile
跟前面编辑源代码的方法类似,在nano中编辑如下所示的内容:
CC := g++-5
# replace this with your correct compiler as identified above
ARCH := core2 # Replace this with your CPU architecture.
# core2 is pretty safe for most modern machines.
CFLAGS := -march=$(ARCH) -O3 -fopenmp -m64 -std=c++11
COMPILE_COMMAND := $(CC) $(CFLAGS)
OUTPUT := my_test
all: omp_test.cpp
$(COMPILE_COMMAND) -o $(OUTPUT) omp_test.cpp
clean:
rm -f *.o $(OUTPUT).*
编辑完成后退出nano回到Terminal,然后在命令下输入:
> make
> ./my_test
刚刚编写的OpenMP程序就会被执行,输出应该如下:
Allocating memory …
Done!
Entering main loop …
Done!
最后是一个可能 Troubling shooting(尽管上面的代码我已经做了调整,应该不会出现下面这个问题): If the make command gives errors like “** missing separator”, then you need to replace the white space (e.g., one or more spaces) at the start of the “$(COMPILE_COMMAND)” and “rm -f” lines with a single tab character.
后续我们还会介绍更多关于OpenMP并行编程方法的技术。
http://mathcancer.blogspot.com.au/2016/01/PrepOSXForCoding-Homebrew.html
最后补刀一个来自Intel的绝佳OpenMP编程入门视频课程:
https://www.youtube.com/watch?v=nE-xN4Bf8XI&feature=youtu.be&list=PLLX-Q6B8xqZ8n8bwjGdzBJ25X2utwnoEG
(全文完)