[f2py] Raise exception from inside wrapped fortran code

James Kermode jrk33 at cam.ac.uk
Thu Dec 18 15:54:45 EET 2008


On 17 Nov 2008, at 09:08, Pearu Peterson wrote:
> James Kermode wrote:
>> The problem is that the aborts can happen several layers further down
>> the Fortran call tree than the entry point called by f2py. I need  
>> some
>> way to immediately "get out" of the Fortran code and return to Python
>> when the abort occurs -- does anyone have any ideas?
>
> Another idea would be executing f2py wrappers in another thread
> and catch Fortran aborts via catching thread kills..

I'm trying to implement this idea but haven't had much success. The  
problem is that when a wrapped fortran function running in a thread  
stops it terminates the entire process, not just its own thread. I've  
tried replacing the stop statement with a call to pthread_exit() but  
this causes the python interpreter to hang.

I've included my test program below (two modules are required because  
f2py gets confused by the bind(c) stuff). Does anyone have any ideas  
on how I can cleanly exit a thread initiated in python from fortran?

Thanks,
James

 > cat thread.f95
module threadstop
   use iso_c_binding
   interface
      subroutine pthread_exit(retval) bind(c)
        use iso_c_binding, only: C_PTR
        type(C_PTR), intent(in), value :: retval
      end subroutine pthread_exit
   end interface
contains
   subroutine stopnow()
     integer, target :: v = 1
     call pthread_exit(c_loc(v))
   end subroutine stopnow
end module threadstop

 > cat threadwrap.f95
module twrap
   use threadstop, only: stopnow
contains
   subroutine dostop()
     call stopnow
   end subroutine dostop
end module twrap

 > gfortran -c thread.f95 -o thread.o
 > f2py -m twrap -c threadwrap.f95 thread.o -lpthread

Python 2.5.2 (r252:60911, Oct  3 2008, 12:21:08)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
 >>> import thread
 >>> import twrap
 >>> thread.start_new_thread(twrap.twrap.dostop, ())
-1341648896
 >>>
[python main thread hangs]
^C





More information about the f2py-users mailing list