ForeignPtr performance

Stefan O'Rear stefanor at
Mon Dec 17 17:10:45 EST 2007

On Mon, Dec 17, 2007 at 02:12:31PM +0300, Bulat Ziganshin wrote:
> 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!

I'd like to elaborate that ptr, as far as the GC is concerned is *not a
pointer at all*, it is an integer memory address.  So it doesn't keep
anything alive, you need to hold on to fptr if you want the value to

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url :

More information about the Glasgow-haskell-users mailing list