2014-11-06 91 views
1

假设与mpif90作为编译过简化FORTRAN代码:调用在FORTRAN子程序而不阻挡主程序

program main 
! 
    use mpi 
    implicit none 
    integer:: j, numtasks, taskid, ierr 
    integer:: master = 0 
! 
    call mpi_init(ierr) 
    call mpi_comm_rank(mpi_comm_world, taskid, ierr) 
! 
    if (taskid .eq. master) then 
     j = 5 
     call child (j) 
    ! do stuff 
    end if 
    call mpi_finalize(ierr) 
! 
end program main 

subroutine child(j) 
! 
    implicit none 
    integer, intent(in):: j 
! do some stuff with j 
end subroutine child 

默认情况下,从主等待主CPU直到子与其计算完成。但是,我希望它在给孩子打电话之后继续完成任务,而孩子也在完成任务。我希望孩子成为主要的子程序,因为我需要将一些数据从主体传递给孩子(但不是相反)。我想知道是否可以在FORTRAN中使用(也许通过使用某种非阻塞子例程调用或多线程(如mpi_comm_spawn))。

回答

1

我会为此使用POSIX线程。也许也是一个OpenMP任务,但我的经验是有限的。我会假定您不会在child中调用任何MPI程序。

在C一个简单的界面

#include <pthread.h> 

void pthread_create_opaque(pthread_t *threadptr, void *procptr, void *dataptr, int *err){ 
// creates a new thread using an opaque pointer to the pthread_t structure 
    *err = pthread_create(threadptr, NULL, procptr, dataptr); 
} 

void pthread_join_opaque(pthread_t *threadptr, int *err) { 
// joines a thread using an opaque pointer to the pthread_t structure 
*err = pthread_join(*threadptr, NULL); 
} 

和Fortran语言

module Pthreads 
    implicit none 

    interface 
    subroutine pthread_create_opaque(threadptr, procptr, dataptr, err) bind(C,name="pthread_create_opaque") 
     use iso_c_binding 
     type(c_ptr) :: threadptr 
     type(c_funptr),value :: procptr 
     type(c_ptr),value :: dataptr 
     integer(c_int),intent(out) :: err 
    end subroutine 

    subroutine pthread_join_opaque(thread, err) bind(C,name="pthread_join_opaque") 
     use iso_c_binding 
     type(c_ptr),value :: thread 
     integer(c_int),intent(out) :: err 
    end subroutine 
    end interface 
end module Pthreads 

你可以调用一个孩子如果是C互操作

subroutine child(j) bind(C) 
! 
    implicit none 
    integer, intent(in):: j 
! do some stuff with j 
end subroutine child 

仅仅作为

type(c_ptr) :: thread 
integer :: err 

call pthread_create_opaque(thread, c_funloc(join), loc(j), err) 

,后来在一些方便的地方(程序结束之前或别的地方)等待它完成其工作

call pthread_join_opaque(thread, err) 

我在时间步长数据的异步输出的MPI并行程序成功地使用这一点。

相关问题