Re: [libdispatch-dev] GCD libdispatch w/Blocks support working on Free (f

From: Robert N. M. Watson <rwatson_at_freebsd.org>
Date: Tue, 6 Oct 2009 21:29:50 +0100
On 6 Oct 2009, at 19:50, Chuck Swiger wrote:

> Hi, Hans--
>
> On Oct 2, 2009, at 5:40 AM, Hans Petter Selasky wrote:
>> Can the Apple's "Blocks" C language extension be used when  
>> programming in the kernel? Or is this a user-space only feature?
>
> While the main benefit of blocks is in conjunction with libdispatch  
> for userland apps, they can be used by themselves, in the kernel or  
> elsewhere.

When a block is instantiated (perhaps not the formal terminology), the  
blocks runtime allocates memory to hold copies of relevant variables  
from the calling scope. This memory allocation may present an issue in  
some calling contexts in the kernel -- in particular, it won't be  
appropriate in contexts were non-sleepable locks are held, interrupt  
threads, etc. While it should be possible to use the primitive in the  
kernel, we may want to think carefully about these implications. Also,  
blocks are currently specific to clang, although with any luck gcc  
will grow them also.

Robert

>
> A block is a closure and starts off living on the stack (although, a  
> block can outlive the stack frame of the caller by being copied over  
> to the heap if needed); the compiler wraps automatic variables which  
> were around in the scope of the caller, turns their type into const  
> (unless you explicitly declare that you need to change a variable by  
> using __block storage keyword, in which case that variable is kept  
> on the heap and accessed by reference) in order to preserve the  
> state until the block runs.
>
> In effect, blocks are normal function invocations which also have an  
> extra argument which is the context or pointer to the saved  
> environment state.  They can be used to implement callbacks and  
> continuations in a clean way, although you do have some overhead  
> with accessing mutable variables via pointer dereference to the  
> struct holding your saved context.  However, most uses of callbacks  
> in C are implemented as functions which accept a void *, which is  
> used to feed the callback function a struct * of some sort, so the  
> end result is fairly similar.
>
> Regards,
> -- 
> -Chuck
>
Received on Tue Oct 06 2009 - 18:29:54 UTC

This archive was generated by hypermail 2.4.0 : Wed May 19 2021 - 11:39:56 UTC