GHC ccall safe VS ccall unsafe

Dear GHC / Haskell Gurus,

I am currently writing a (medium-sized) Haskell server application using GHC that (heavily) uses C-side C library functions via FFI. In other words, there are multiple FFI C calls made by the server thread while serving the client request.

I am currently calling all C functions unsafely ( unsafe ccall ) to minimize the overhead. But the tradeoff is that unsafe ccalls cannot be ruled out by GHC RTS, which means that all other Haskell threads will block until the C function returns. This can be problematic if the C function takes too long.

On the other hand, secure ccalls are more expensive, but they will run on separate OS threads and will not block GHC worker threads.

I think what I'm trying to ask here is how you can reasonably make a better choice: create a secure ccall or an unsafe ccall ? For example, I don't want to do an expensive safe ccall if the C function is short and trivial, but if the C function takes a long time to return (computation of cpu-heavy, I / O operations, etc.) then making an unsafe call is problematic since it blocks the worker thread . Is there some sort of approximate threshold t

so that if the C function takes longer t

to complete, then make it a safe ccall and an otherwise unsafe ccall?

Hopefully this question makes sense and if there is anything unclear, please feel free to comment.

Thant for your help in advance!

+3


source to share


1 answer


The rule of thumb is as follows:

  • Do everything safe

    .
  • If profiling shows a performance issue with FFI call overhead, carefully consider whether the semantics are appropriate unsafe

    for hotspot calls.
  • If profiling has identified a performance issue in the overhead of an safe

    FFI call , and semantic analysis of the call shows unsafe

    it won't break anything, then consider changing to unsafe

    expect the call to wait better than 1 millisecond.


Don't skip the first two steps. unsafe

has more potential problems than just blocking RTS.

+3


source







All Articles