ForeignPtr performance
Bulat Ziganshin
bulat.ziganshin at gmail.com
Mon Dec 17 06:12:31 EST 2007
Hello Simon,
Monday, December 17, 2007, 1:33:19 PM, you wrote:
>>> My question is: what exactly does GHC.Prim.touch# do? This appears to
>>
>> it's a no-op (for ghc 6.6+ at least). its only task is to notify ghc
>> optimizer that data were accessed so it doesn't free the memory
> Yes, exactly. touch# generates no code, but it is vitally important
> because if the ForeignPtr is referencing data in the heap (like
> mallocForeignPtrBytes does), it prevents the data from being GC'd before
> the operation completes.
a bit more details for Scott:
generated code is like this:
ptr <- unsafeForeignPtrToPtr fptr
yourAction ptr
touch# fptr
without touch, the *last* action where fptr involved is its conversion
to ptr. GHC Runtime (not optimizer as i said) have no idea that ptr
and fptr is the same object, so after conversion it feels free to
dispose object pointed by fptr if GC occurs. this means that during
execution of your action data pointed by fptr/ptr may be suddenly
freed, allocated by other object, bang!
the touch pseudo-action is performed *after* your action and
references fptr again. so Runtime thinks "there is one more usage of
fptr after yourAction" and it doesn't dispose this chunk of memory if
GC occurs during your action
(unfortunately it's not mentioned anywhere on the Web)
--
Best regards,
Bulat mailto:Bulat.Ziganshin at gmail.com
More information about the Glasgow-haskell-users
mailing list