I am newbie to both Fortran and C++, working on a task to couple two programs written in Fortran and C++.
I am trying to create a pthread(detached) wrapper and call it from my Fortran subroutine and pass a cpp function to it. I wrote some code by following this link Calling a subroutine in FORTRAN without blocking the main program.
I get run time error like below, when i execute it.
Program received signal SIGSEGV: Segmentation fault - invalid memory reference.
Backtrace for this error:
I compiled using the following commands
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++
Here is the minimal code where i can reproduce the error.
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
where PCModel
is the C++ function to be executed by pthread.
pcmodel.cpp
#include <iostream>
#include "pthreads_interface.h"
using namespace std;
void PCModel(){
cout<<"PCModel is called"<<endl;
}
extern "C" void PCModel_(){
PCModel();
}
Ideally both my Fortran and C++ code should run in parallel, once the fortran code triggers the thread to start the C++ function(PCModel
)
It would be great, if some one could check the code and help me out.