Skip to content

Instantly share code, notes, and snippets.

@bennofs
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bennofs/95959bbe8dc336e4c4ca to your computer and use it in GitHub Desktop.
Save bennofs/95959bbe8dc336e4c4ca to your computer and use it in GitHub Desktop.
Concurrency and the FFI
#include <stdio.h>
int bottom(int a) {
int i = 0;
for(i = 0; i < 5; ++i) {printf("%d\n", a);sleep(1);}
return a;
}
int bottom(int a);
$ gcc -c -o cbit.o cbit.c
$ ghc -threaded --make ffi.hs cbit.o -rtsopts
{-# LANGUAGE ForeignFunctionInterface #-}
import Foreign.C
import Control.Concurrent
main = runInUnboundThread $ do
forkIO $ do
safeBottom 1
return ()
forkIO $ do
unsafeBottom 2
return ()
print "Pass (not expected)"
foreign import ccall "cbit.h bottom" safeBottom :: CInt -> IO CInt
foreign import ccall unsafe "cbit.h bottom" unsafeBottom :: CInt -> IO CInt
$ ./ffi +RTS -N1
1
2
1
2
1
2
1
2
1
2
"Pass (not expected)"

$ ./ffi +RTS -N2
1
2
1
2
1
2
1
2
1
2
"Pass (not expected)"

$ ./ffi +RTS -N3
1
2
"Pass (not expected)"
1
2
1
2
1
2
1
2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment