2014-11-06 63 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並行程序成功地使用這一點。

相關問題