2017-04-17 63 views
2

我是Fortran和C++的新手,正在開發一個任務來連接兩個用Fortran和C++編寫的程序。Fortran的Pthread包裝器

我想創建一個pthread(分離)包裝並從我的Fortran子例程中調用它並將cpp函數傳遞給它。我通過以下鏈接Calling a subroutine in FORTRAN without blocking the main program寫了一些代碼。

當我執行它時,出現如下所示的運行時錯誤。

Program received signal SIGSEGV: Segmentation fault - invalid memory reference. 

Backtrace for this error: 

我使用下列命令

gfortran-mp-4.7 -c pthread_mod.f90 
g++-mp-4.7 -c -std=c++11 pcmodel.cpp 
gfortran-mp-4.7 -c mainFort.F 
gfortran-mp-4.7 pthreads_module.o pcmodel.o mainFort.o -o test -lstdc++ 

編譯的下面是最少的代碼,其中i可以再現錯誤。

Pthreads_interface.h

extern "C" void pthread_create_opaque(pthread_t *threadptr, void *(**procptr)(void *), int *comerr){ 
    // creates a new thread using an opaque pointer to the pthread_t structure 
    pthread_attr_t attr; 
    pthread_attr_init(&attr); 
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); 
    *comerr = pthread_create(threadptr, &attr, (*procptr), NULL); 
} 

pthreads_module.f90

module pthreads_module 
implicit none 
interface 

    subroutine pthread_create_opaque (threadptr, procptr, comerr) bind(C,name="pthread_create_opaque") 
     USE ISO_C_BINDING 
     type(c_ptr) :: threadptr 
     type(c_funptr),value :: procptr 
     integer(c_int),intent(out) :: comerr 
    end subroutine 

    subroutine PCModel() bind (c,name="PCModel_") 
     USE ISO_C_BINDING 
    end subroutine PCModel 

    end interface 
end module pthreads_module 

mainFort.F

program test 
call BCL00 
end program test 

    SUBROUTINE BCL00 
    use pthreads_module 
    USE ISO_C_BINDING 
    implicit none 
    type(c_ptr) :: threadptr 
    integer :: comerr 
    call pthread_create_opaque(threadptr, 
&   c_funloc(PCModel),comerr) 

    END 

其中PCModel是由並行線程執行的C++函數。

pcmodel.cpp

#include <iostream> 
#include "pthreads_interface.h" 
using namespace std; 

void PCModel(){ 
     cout<<"PCModel is called"<<endl; 
} 

extern "C" void PCModel_(){ 
    PCModel(); 
} 

理想的情況下我的Fortran和C++代碼都應該並行運行,一旦Fortran代碼觸發線程啓動C++函數(PCModel

這將是巨大的,如果有人能夠檢查代碼並幫助我。

+0

是的,它沒有被宣佈,但我在我的。 – raghu

+0

聽起來不錯,會做到。 – raghu

+0

@Vladimir F試了一下。它說'調用pthread_create_opaque(c_loc(threadptr),錯誤:類型不匹配參數'threadptr'在(1);傳遞實型(4)類型(c_ptr)' – raghu

回答

0

在Pthreads_interface.h我改變procptr(*procptr)傳遞的方式procptr

extern "C" void pthread_create_opaque(pthread_t *threadptr, void *(*procptr)(void *), int *comerr){ 
// creates a new thread using an opaque pointer to the pthread_t structure 
pthread_attr_t attr; 
pthread_attr_init(&attr); 
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); 
*comerr = pthread_create(threadptr, &attr, procptr, NULL); 
} 

現在,它在運行時Segmentation fault和主程序繼續無需等待的線程。

+0

謝謝@Vladimir F – raghu