[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: C calling Scheme and garbage collection

From: Mark H Weaver
Subject: Re: C calling Scheme and garbage collection
Date: Sun, 30 Jun 2019 21:26:24 -0400
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/26.1 (gnu/linux)

Hi Isaac,

Isaac Jurado <address@hidden> writes:

> I'm playing with event loop libraries implemented in C (libev,
> libevent, etc... in my case libsystemd), but configuring them from
> Guile.
> The qsort example in the documentation [1] seems safe because the
> qsort C function directly calls back, so the callback Scheme bindings
> stay referenced (by the Scheme code calling qsort) during all the C
> code execution.
> Now, in C event loops the situation is different.  There is one call
> to configure the event callback, in which the function and data
> pointers are lent to the loop; and then there is the main loop or the
> single iteration call.
> The way I see it, suppose I add a timer.  I call one C function
> passing a (proceudre->pointer) and an (scm->pointer).  In a future
> time, those pointers will be used by the C event loop.  If a garbage
> collection happens in the middle, the results of (procedure->pointer)
> and (scm->pointer) may have been reclaimed by the time the C event
> loop calls back.

That's right.  When passing pointers to GC-allocated blocks to arbitrary
C code, you must take care to keep GC-visible references to those
pointers until they are no longer needed.  This will not happen
automatically, unless the C code was specifically written to ensure that
the references will be visible to the GC.

BDW-GC does *not* scan arbitrary C data structures.  In particular,
blocks allocated using C 'malloc' or C++ 'new' are not scanned.

> However, I've tried forcing (gc) between the two steps mentioned and
> it looks to be working fine.

As Greg mentioned, this isn't a sufficient test.

In general, I would avoid relying on experiments to determine what is
safe to do.  Experiments can only tell you how the tested version(s)
behave.  They cannot give you assurances about how future versions are
supposed to behave.

> I have also reviewed some of the code [2][3] and some additional weak
> references seem to be created.

Those weak references do not eliminate the need to keep GC-visible
references to the relevant objects.  They merely ensure that *if* you
keep a reference to the returned pointer, the other associated data
structures are also kept alive.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]