gnustep-dev
[Top][All Lists]
Advanced

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

Re: Grand Central


From: Jens Ayton
Subject: Re: Grand Central
Date: Sun, 14 Jun 2009 15:27:53 +0200

On Jun 14, 2009, at 14:53, Pete French wrote:

http://images.apple.com/macosx/technology/docs/GrandCentral_TB_brief_20090608.pdf

Interesting - that ^{ syntax to describe a block is somewhat ugly, and it doesnt give any deats of how you associate data with a block (which is necessary if
you want to get rid of locks).

There are two ways to pass data into blocks: constant copies from the parent scope, and mutable access to "block variables" in the parent scope (the latter makes blocks true closures). Here is a simple example:

typedef int (^IntIntBlock)(int);

IntIntBlock MakeExampleThing(int initial, int delta)
{
    __block int accum = initial;
    int (^block)(int) = ^(int i) { return accum += i + delta; };
    return Block_copy(block);
}


In the block created above, accum is a block variable, and delta is a const copy. If MakeExampleThing() is called twice, they get separate copies of accum, so there's your data associated with the block. If two blocks were created in the same function, both referring to accum, they would share it.

int main(void)
{
    int (^a)(int) = MakeExampleThing(5, 2);
    int (^b)(int) = MakeExampleThing(1, 0);

    printf("%i\n", a(3));  // prints 10
    printf("%i\n", b(1));  // prints 2

    Block_release(a);
    Block_release(b);
    return 0;
}


The block runtime is set up to allow blocks to be ObjC objects, so that Block_copy() and Block_release() can be replaced with retain and release messages. (Block_copy() is conceptually a retain operation, although it actually does copy in the above example because the block is initially created on the stack.)

In case the new syntax and manual memory management overhead gets in the way in the above code, here's a Javascript equivalent:

function MakeExampleThing(initial, delta)
{
    return function(i)
    {
        return initial += i + delta;
    }
}


I can't work out if GCD is supposed to be an extension for OSX or an extension to Objective-C itself. Obviously the block syntax requiures a language extension,
but how do the bits fit together from there onward ?

Other than blocks, as far as I can see (I don't have Snow Leopard seeds) it's "just" a library and an optimized thread scheduler.


--
Jens Ayton





reply via email to

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