ForeignPtr performance

Scott Dillard sedillard at ucdavis.edu
Mon Dec 17 10:24:45 EST 2007


Thanks for the response guys.

I'm still curious as to the specific mechanism by which a strictly
compile-time function affects the run-time behavior of the GC. Bulat
says that touch# makes the runtime aware that the fptr object is still
in use, but how does it do this if, at runtime, it doesn't do
anything? Does if affect the scheduling of collections? Does it mark
the fptr object with some flag when its allocated? What if, for
example, if I put the touch# behind a branch that is conditional on
run-time values? How would this affect things?

I'm sure the answer to this is detailed and involves a lot of
specifics about GHC that I probably won't grasp, and maybe it isn't
appropriate for the whole list, but if there happens to be a short
answer, or there's a reference you can point me to, I'd appreciate it.

Thanks,
Scott



On Dec 17, 2007 4:12 AM, Bulat Ziganshin <bulat.ziganshin at gmail.com> 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!
>
> 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