2012-01-17 8 views
5

A continuación se muestra un código Haskell/C FFI que genera un error de programación en el tiempo de ejecución (GHC 7.0.3, Mac OS 10.7, x86_64). Busqué la explicación del error pero no encontré nada relevante.Programe el error al llamar al C-FFI de subprocesos múltiples con la función de devolución de llamada Haskell

C Código (mt.c):

#include <pthread.h> 
#include <stdio.h> 

typedef void(*FunctionPtr)(int); 

/* This is our thread function. It is like main(), but for a thread*/ 
void *threadFunc(void *arg) 
{ 
    FunctionPtr fn; 
    fn = (FunctionPtr) arg; 
    fn(1); //call haskell function with a CInt argument to see if it works 
} 

void create_threads(FunctionPtr* fp, int numThreads) 
{ 
    pthread_t pth[numThreads]; // array of pthreads 
    int t; 
    for (t=0; t < numThreads;){ 
    pthread_create(&pth[t],NULL,threadFunc,*(fp + t)); 
    t++; 
    } 

    printf("main waiting for all threads to terminate...\n"); 
    for (t=0; t < numThreads;t++){ 
    pthread_join(pth[t],NULL); 
    } 
} 

código Haskell (t.hs) - que llama create_threads en mt.c anterior con Storable Vector de FunPtr a la función Haskell f (después de aplicar primeros tres argumentos para f):

{-# LANGUAGE BangPatterns #-} 
import Control.Concurrent (forkIO, threadDelay, MVar, newEmptyMVar, putMVar, takeMVar) 
import qualified Data.Vector.Storable.Mutable as MSV 
import qualified Data.Vector.Storable as SV 
import Control.Monad.Primitive (PrimState) 
import Control.Monad (mapM, forM_) 
import Foreign.Ptr (Ptr, FunPtr) 
import Foreign.C.Types (CInt) 


type Length = CInt 

-- | f is a function that is called back by create_threads in mt.c 
f :: MVar Int -> MSV.MVector (PrimState IO) CInt -> Length -> CInt -> IO() 
f m v l x = do 
       !i <- takeMVar m 
       case (i< fromIntegral l) of 
       True -> MSV.unsafeWrite v i x >> print x >> putMVar m (i+1) 
       False -> return() -- overflow 

-- a "wrapper" import gives us a converter for converting a Haskell function to a foreign function pointer 
foreign import ccall "wrapper" 
    wrap :: (CInt -> IO()) -> IO (FunPtr (CInt -> IO())) 

foreign import ccall safe "create_threads" 
    createThreads :: Ptr (FunPtr (CInt -> IO())) -> CInt -> IO() 

main = do 
    let threads = [1..4] 
    m <- mapM (\x -> newEmptyMVar) $ threads 
    -- intialize mvars with 0 
    forM_ m $ \x -> putMVar x 0 
    let l = 10 
    -- intialize vectors of length 10 that will be filled by function f 
    v <- mapM (\x -> MSV.new l) threads 
    -- create a list of function pointers to partial function - the partial function is obtained by applying first three arguments to   function f 
    lf <- mapM (\(x,y) -> wrap (f x y (fromIntegral l))) $ zip m v 
    -- convert above function list to a storable vector of function pointers 
    let fv = SV.fromList lf 
    -- call createThreads with storable vector of function pointers, and number of threads - createThreads will spawn threads which will use function pointers for callback 
    SV.unsafeWith fv $ \x -> createThreads x (fromIntegral $ length threads) 

Por favor, ignore las partes inseguras en el código - mi objetivo aquí es probar la devolución de llamada usando Haskell FFI con multi-thre código C aded. Cuando compilo, y funciono, me sale el error a continuación:

$ ghc -O2 t.hs mt.c -lpthread 
[1 of 1] Compiling Main    (t.hs, t.o) 
Linking t ... 
$ ./t 
main waiting for all threads to terminate... 
t: schedule: re-entered unsafely. 
    Perhaps a 'foreign import unsafe' should be 'safe'? 
$ uname -a 
Darwin desktop.local 11.2.0 Darwin Kernel Version 11.2.0: Tue Aug 9 20:54:00 PDT 2011; root:xnu-1699.24.8~1/RELEASE_X86_64 x86_64 
$ ghc --version 
The Glorious Glasgow Haskell Compilation System, version 7.0.3 

El error de programación que ocurre sólo si tengo los hilos C vuelven a llamar la función f Haskell. Supongo que es más probable que haya un error en mi código, que un error en una de las bibliotecas o GHC. Por lo tanto, me gustaría consultar aquí primero para ver los punteros sobre la causa del error.

+1

Dado que encontró la solución, debe publicarla como respuesta. –

+0

Gracias, @john. Acabo de agregar la respuesta. – Sal

+0

@hammar, gracias por la edición para reflejar la respuesta publicada. – Sal

Respuesta

2

En este caso, se produjo el error schedule porque el código haskell se compiló sin la opción -threaded.

El código de haskell llama a la función C create_threads que genera múltiples hilos para la función C threadFunc. threadFunc vuelve a llamar a la función Haskell f. Por lo tanto, aunque el código de Haskell se compila sin la opción -threaded, aún resulta en que múltiples subprocesos C ejecutan f.

GHC Runtime Scheduler ha detectado que esta supervisión de ejecución de varios subprocesos sin tiempo de ejecución de subprocesos es buena y se marca como un error. Eso es mucho mejor que un bloqueo críptico en tiempo de ejecución. Me di cuenta de la supervisión cuando revisé el código rts/schedule.c en la base de código GHC, y vi el comentario a continuación. Me avisó acerca de threaded runtime no habilitado:

// Check whether we have re-entered the RTS from Haskell without 
// going via suspendThread()/resumeThread (i.e. a 'safe' foreign 
// call). 
Cuestiones relacionadas