I'm creating an FFI module to a library in C which wants a 1-time, non-reentrant function to be called before anything else is. This call is idempotent, but stateful, so I could just call it in every Haskell call. But it's slow and due to non-reentrancy it could cause conflicts.
So is this the right time to use unsafePerformIO? I could wrap a Bool in an unsafe IORef or MVar to make these initialization calls idempotent by ignoring subsequent calls (calls where the global, hidden IORef state is False).
If not, what is the right way to do this?
I prefer the approach of initializing once and providing an unforgeable token as evidence that you have initialized the machine.
So your evidence would be:
which you export abstractly.
Then your initialization function can return this evidence.
Now, you need to pass that proof to your API:
etc.
You can now wrap this stuff up with a monad, or some higher order initialization environment to make it cleaner, but that's the basic idea.
The problem with initializing C libraries using hidden state is that you end up either not being able to parallelize access to the library, or having problems in GHCi, mixing compiled and bytecode, with two different versions of the C library loaded (which will fail with a linker error).
I'd like to note that currently some new trick is suggested for/instead of
withSocketsDo
by Neil Mitchell, based onevaluate
("Forces its argument to be evaluated to weak head normal form when the resultant IO action is executed."):Not necessarily this is a beautiful idea...
(See also his answer announcing this update in the library.)