[Haskell-cafe] Is it safe to create global variables using unsafePerformIO?
Ryan Yates
fryguybob at gmail.com
Wed Jan 29 15:58:18 UTC 2014
You would need the NOINLINE pragma:
{-# NOINLINE eventObj_ #-}
eventObj_ :: Ptr Event
eventObj_ = unsafePerformIO malloc
I would avoid this sort of global state in general. It isn't clear that
this will give an improvement in performance and what could otherwise
possible be a thread safe API is no longer thread safe. Global TVars and
MVars are much more compelling as they are thread safe and represent some
global synchronization in your program.
On Wed, Jan 29, 2014 at 10:03 AM, Ömer Sinan Ağacan <omeragacan at gmail.com>wrote:
> I was also wondering a similar thing. I'm writing FFI for a C library.
> Library has a function like:
>
> int pollEvent(EventType* event);
>
> Instead of malloc'ing a new EventType in a FFI call for this functions:
>
> pollEvent :: IO Event
> pollEvent = do
> ev <- malloc
> ret <- cPollEvent ev
> -- check if ret is 0 etc.
> peek ev
>
> I was wondering if something like this is also safe:
>
> eventObj_ :: Ptr Event
> eventObj_ = unsafePerformIO malloc
>
> pollEvent :: IO Event
> pollEvent = do
> ret <- cPollEvent eventObj_
> -- check if ret is 0 etc.
> peek eventObj_
>
> This is one malloc cheaper for every call, and differences are not
> visible from user side. Still, I did not use this in my FFI bindings
> because I was not sure how safe is this approach. Any ideas on this?
>
>
> ---
> Ömer Sinan Ağacan
> http://osa1.net
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20140129/fa6587a4/attachment.html>
More information about the Haskell-Cafe
mailing list