[英]Pthread Wrapper for Fortran
我是Fortran和C ++的新手,致力於將兩個用Fortran和C ++編寫的程序耦合在一起的任務。
我試圖創建一個pthread(獨立的)包裝器,並從我的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
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
是要由pthread執行的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 ++函數( PCModel
),我的Fortran和C ++代碼應該並行運行
如果有人可以檢查代碼並幫幫我,那就太好了。
在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
並且主程序無需等待線程即可繼續運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.