Reply to comment

Code Execution and Dispatch Thoughts... Blocks: Closures for Obj-C

I've re-reading a post I found on Hacker News A simple job queue with Grand Central Dispatch. It's what it says - a queue using GCD, a new OS X (or is it ObjC) dispatcher that uses closures, aka Blocks in Obj C, rather than (I guess) other kinds of objects.

The issue of really understanding threaded styles of programming versus the callback/closure style is a somewhat mathematical problem. Can you prove that a threaded program can be implemented by a callback-based program, and vice versa. Intuition says "no", but experience tells me "yes, if you are careful."

With callbacks, you need to check return values, poll when you should poll rather than block, and exit your routine cleanly (or at least exit). That's really not that different from cooperative threading, where the program relinquishes control to other threads, rather than having the environment interrupting the execution of a thread.

The main difference is "how you write the code" and how the code executes.

In a threaded program, you might have code written like this:

function A
   one;
   two;
   sync with B;
   three;
end

function B
   four;
   sync with C;
   five;
end

function C
   six;
   seven;
end

dispatch thread with A;
dispatch thread with B;
dispatch thread with C;

The order might be:
one; two; four; six; seven; five; three;

In a functional language it might be:

function init
  set the callback of A to B;
  set the callback of B to C;
  one;
  two;
  call A;
end

function A
  call callback;
  three;
end

function B
  four;
  call callback;
  five;
end

function C
   six;
   seven;
end

The execution order is:
one; two; four; six; seven; five; three;

That's the same execution order. The main difference is, in the threaded style, that MIGHT be the execution order. In the functional/closures style, that IS the execution order.

Also, with closures, each function is a closure, and contains the state of the environment at the time when the function was set as the callback to another function. In a threaded system, each thread contains its own environment (the stack).

Initially, I started with a lot of "threads vs. callbacks" thinking, but now, I'm inclined to think of them as complementary techniques. Threads and callbacks both allow us to write sequential programs that operate in a non-sequential, parallelized reality. Threads allow coders to put linearity into the code, and callbacks force us to break the task down into smaller chunks, allowing the program (at runtime) to reassemble these parts into data structures that are executed in response to the parallelized reality.

Reply

The content of this field is kept private and will not be shown publicly.
  • Lines and paragraphs break automatically.

More information about formatting options

12 + 4 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.