2

我是 Fortran 和 C++ 的新手,致力于将两个用 Fortran 和 C++ 编写的程序耦合起来。

我正在尝试创建一个 pthread(detached) 包装器并从我的 Fortran 子例程中调用它并将一个 cpp 函数传递给它。我按照这个链接在 FORTRAN 中调用一个子程序而不阻塞主程序来编写一些代码。

当我执行它时,我得到如下运行时错误。

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++

这是我可以重现错误的最小代码。

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

主堡

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

PCModelpthread 执行的 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

如果有人可以检查代码并帮助我,那就太好了。

4

1 回答 1

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没有等待线程的情况下运行,主程序继续运行。

于 2017-04-19T07:57:43.820 回答