MPI和线程

时间:2011-08-23 23:14:00

标签: c mpi

我是MPI的初学者,我想以下列方式使用MPI线程。某些进程(所有偶数procs)生成线程并执行阻塞等待以接收消息。每个proc生成的线程数是一个命令行参数。因此,如果有4个过程,则进程0和2产生一个线程。现在,我希望进程0和2都向所有线程发送消息。例如,进程0向自身发送消息并向进程2发送消息,proc 2将其发送到proc 0和它自己。 这是我的代码看起来像,它显然没有做到所需的。它只是等待接收消息。我哪里错了?

谢谢!

  typedef struct {
     int id;
  } struct_t;

void *hello(void *arg)
{
    int rank;
    char mystr[10];
    MPI_Status status;
    struct_t *fd=(struct_t *)arg;
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    printf("Rank %d is waiting in thread %d for my message\n", rank, fd->id);

    if(rank%2 ==0){
            MPI_Recv(mystr, 10, MPI_CHAR, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &status);
            printf("Thread %d on rank %d received %s\n", fd->id, rank, mystr);
    }

    return (NULL);
}

void spawn_thread(int n)
{
    int size,rank, i;
    pthread_t *threads;
    pthread_attr_t pthread_custom_attr;
    struct_t *fd;
    threads=(pthread_t *)malloc(n*sizeof(*threads));
    pthread_attr_init(&pthread_custom_attr);
    fd=(struct_t *)malloc(sizeof(struct_t)*n);

    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);

    /* Start up thread */
    for (i=0; i<n; i++)
    {
            fd[i].id=i;
     //       printf("My rank is %d and I created thread #%d\n", rank, i);
            pthread_create(&threads[i], &pthread_custom_attr, hello, (void *)(fd+i));
    }

    /* Synchronize the completion of each thread. */
    for (i=0; i<n; i++)
    {
            pthread_join(threads[i],NULL);
    }
    free(fd);
}
 void main(int argc, char ** argv)
{
    int n,i, provided, claimed;
    int rank, size, errs;

    MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);

    if (argc != 2)
    {
            printf ("Usage: %s n\n  where n is no. of threads\n",argv[0]);
            exit(1);
    }

    n=atoi(argv[1]);
    if ((n < 1) || (n > MAX_THREAD))
    {
            printf ("The no of thread should between 1 and %d.\n",MAX_THREAD);
            MPI_Abort(MPI_COMM_WORLD,-1);
    }

  if(rank%2 == 0)
            spawn_thread(n);

    if(rank%2 == 0){

                    printf("My rank is %d and I am sending Hello!\n", rank);
                    MPI_Send("HELLOOO", 10, MPI_CHAR, rank, 0, MPI_COMM_WORLD);
          }

    MPI_Finalize();
}

1 个答案:

答案 0 :(得分:1)

我并不完全确定我理解你想要实现的目标,但请注意,所有排名均匀的进程的线程都会阻塞接收,因此没有人会运行发送代码。您排名奇怪的进程的线程只是立即开始和结束,因为它们不会做任何事情。

如果以下情况可能如下:

    if(rank%2 == 0){
      printf("My rank is %d and I am sending Hello!\n", rank);
      MPI_Send("HELLOOO", 10, MPI_CHAR, rank, 0, MPI_COMM_WORLD);
    }

应该是这样的:

    if(rank%2 != 0)

这样你的奇数排名进程'至少会发送命令?

或者,你需要在spawn_thread函数之外移动'join'代码,并在调用send之后进行连接。

希望这有帮助。