0

考虑以下 OpenMP 代码片段,它使用中间共享变量在两个线程之间传输私有数据

#pragma omp parallel shared(x) private(a,b)
{
    ...
   a = somefunction(b);
   if (omp_get_thread_num() == 0) {
      x = a;
   }
}
#pragma omp parallel shared(x) private(a,b)
{
  if (omp_get_thread_num() == 1) {
    a = x;
  }
  b = anotherfunction(a);
  ...
}

我将(在伪代码中)需要使用单面消息传递库将私有数据从一个进程传输到另一个进程。有任何想法吗?

4

1 回答 1

3

这是可能的,但是涉及到更多的“脚手架”——毕竟,您是在可能完全不同的计算机之间进行数据通信。

此类事情的协调是在可从其他处理器访问的数据窗口之间完成的,并且通过协调该数据访问的锁定/解锁操作来完成。锁并不是真正意义上的互斥锁,但它们更像是协调对窗口的数据访问的同步点。

我现在没有时间详细解释这一点,但下面是使用 MPI2 在没有共享内存的系统中执行共享内存标记之类的示例:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "mpi.h"

int main(int argc, char** argv)
{
    int rank, size, *a, geta;
    int x;
    int ierr;
    MPI_Win win;
    const int RCVR=0;
    const int SENDER=1;

    ierr = MPI_Init(&argc, &argv);
    ierr |= MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    ierr |= MPI_Comm_size(MPI_COMM_WORLD, &size);

    if (ierr) {
        fprintf(stderr,"Error initializing MPI library; failing.\n");
        exit(-1);
    }

    if (rank == RCVR) {
        MPI_Alloc_mem(sizeof(int), MPI_INFO_NULL, &a);
        *a = 0;
    } else {
        a = NULL;
    }

    MPI_Win_create(a, 1, sizeof(int), MPI_INFO_NULL, MPI_COMM_WORLD, &win);

    if (rank == SENDER) {
        /* Lock recievers window */
        MPI_Win_lock(MPI_LOCK_EXCLUSIVE, RCVR, 0, win);

        x = 5;

        /* put 1 int (from &x) to 1 int rank RCVR, at address 0 in window "win"*/
        MPI_Put(&x, 1, MPI_INT, RCVR, 0, 1, MPI_INT, win);

        /* Unlock */
        MPI_Win_unlock(0, win);
        printf("%d: My job here is done.\n", rank);
    }

    if (rank == RCVR) {
        for (;;) {
            MPI_Win_lock(MPI_LOCK_EXCLUSIVE, RCVR, 0, win);
            MPI_Get(&geta, 1, MPI_INT, RCVR, 0, 1, MPI_INT, win);
            MPI_Win_unlock(0, win);

            if (geta == 0) {
                printf("%d: a still zero; sleeping.\n",rank);
                sleep(2);
            } else
                break;
        }
        printf("%d: a now %d!\n",rank,geta);
        printf("a = %d\n", *a);
    MPI_Win_free(&win);
    if (rank == RCVR) MPI_Free_mem(a);
    MPI_Finalize();

    return 0;
}
于 2011-05-07T21:41:37.397 回答