这可能是一个愚蠢的问题,无论如何我正在研究一个令人尴尬的并行问题。我可以将工作划分为可以并行执行的独立任务(无通信)。
在shell script.sh
中,可以使用以下内容:
#!/bin/bash
let MY_ID=${OMPI_COMM_WORLD_RANK}
./a.out $MY_ID
在prog.c
我们有一个简单的独立程序:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[]){
int myid = atoi(argv[1]);
if(myid%2==0)
printf("\nI am %d and I am an even process\n", myid);
else
printf("\nI am %d and I am an odd process\n", myid);
return 0;
}
最后,用12个不同的处理器执行程序:
mpirun -np 12 script.sh
我的问题是,是否可以使用OpenMP和OMP_NUM_THREADS
等环境变量做同样的事情?
答案 0 :(得分:1)
没有OpenMP环境变量,当以您指定的方式传递给程序时,将为每次调用程序赋予不同的值。如果您考虑OpenMP的工作方式,您可能会像我一样认为这没有多大意义 - 因为OpenMP程序是作为线程集合实现的。这与MPI的操作模型形成鲜明对比,其中每个过程都是一个单独的过程,支持一个用于进程间通信的库 - 在这种情况下,每个进程都有一个唯一的标识符来促进通信。当OpenMP程序执行线程之间的通信受共享内存位置上的操作影响,而不是通过将消息传递给指定的线程。
顺便说一句,你并没有真正编写MPI程序,只是使用其环境提供的一个工具来使shell脚本编写更容易一些。你可以很容易地编写一个shell脚本,在没有MPI环境的情况下为每个程序调用发送一个不同的id - 你可以对OpenMP程序的调用做同样的事情。虽然如果你的程序真的是独立的,你也会这么做,我不知道。
答案 1 :(得分:-1)
将其作为评论发布时间过长。实际上,这种并行处理对于集合建模很有用。当程序运行不同的初始条件时,每次运行会创建不同的文件夹或输出文件。
我想到了这个:
export OMP_NUM_THREADS=4
g++ prog.cpp -fopenmp
./a.out
在prog.cpp
我们有:
#include<stdio.h>
#include<stdlib.h>
#include<omp.h>
#include<string>
using std::string;
int main(){
int nthreads, tid;
string cmd;
#pragma omp parallel private(tid)
{
tid = omp_get_thread_num();
cmd = "echo 'this is a test. I am thread :' " + std::to_string(tid) ;
system(cmd.c_str()); //each thread can creat a folder and run a script
// system("./my_script.sh");
}
return 0;
}
输出如下:
this is a test. I am thread : 0
this is a test. I am thread : 3
this is a test. I am thread : 2
this is a test. I am thread : 1