% mpirun -np 2 sat0) 0110111110011001 0) 0110111111011001 0) 0110111110111001 1) 1010111110011001 1) 1110111110011001 1) 1010111111011001 1) 1110111111011001 1) 1010111110111001 1) 1110111110111001 Process 0 is done Process 1 is done
三个 CPU
1 2 3 4 5 6 7 8 9 10 11 12
% mpirun -np 3 sat0) 0110111110011001 0) 1110111111011001 2) 1010111110011001 1) 1110111110011001 1) 1010111111011001 1) 0110111110111001 0) 1010111110111001 2) 0110111111011001 2) 1110111110111001 Process 1 is done Process 2 is done Process 0 is done
输出分析
输出顺序仅部分反映并行计算机内部输出事件的顺序
如果进程 A 打印两条消息,则第一条消息将在第二条之前出现
如果进程 A 在进程 B 之前调用 printf,则不能保证进程 A 的消息会出现在进程 B 的消息之前
改进程序
希望找到解决方案的总数
将总和规约适用于这个程序
规约是一个集合的通信
修改
修改函数 check_circuit
如果电路满足输入组合,则返回 1
否则返回 0
每个进程保持它找到的可满足电路的本地计数
在 for 循环后执行归约
新的声明和代码
1 2 3 4 5 6 7
int count; /* Local sum */ int global_count; /* Global sum */ intcheck_circuit(int, int);
count = 0; for (i = id; i < 65536; i += p) count += check_circuit (id, i);
MPI_Reduce
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
intMPI_Reduce(void *operand, /* addr of 1st reduction element */ void *result, /* addr of 1st reduction result */ int count, /* reductions to perform */ MPI_Datatype type, /* type of elements */ MPI_Op operator, /* reduction operator */ int root, /* process getting result(s) */ MPI_Comm comm /* communicator */ )
MPI_Reduce (&count, &global_count, 1, MPI_INT, MPI_SUM, 0,//only process 0 will get the result MPI_COMM_WORLD); if (!id) printf ("There are %d different solutions\n",global_count);
第二个程序执行结果
1 2 3 4 5 6 7 8 9 10 11 12 13
% mpirun -np 3 seq20) 0110111110011001 0) 1110111111011001 1) 1110111110011001 1) 1010111111011001 2) 1010111110011001 2) 0110111111011001 2) 1110111110111001 1) 0110111110111001 0) 1010111110111001 Process 1 is done Process 2 is done Process 0 is done There are 9 different solutions