Thunks? (was Re: Covariant returns)

Matthew Economou <>
23 Nov 1999 12:56:46 -0500

          From comp.compilers

Related articles
Covariant returns (Lakshman KNVSM) (1999-11-23)
Thunks? (was Re: Covariant returns) (Matthew Economou) (1999-11-23)
| List of all articles for this month |

From: Matthew Economou <>
Newsgroups: comp.compilers
Date: 23 Nov 1999 12:56:46 -0500
Organization: First Church of B1FF and BRAK! (Reformed)
References: 99-11-131
Keywords: code

>>>>> "LK" == Lakshman KNVSM <> writes:

        LK> [This came up a couple of days ago. Either with function
        LK> wrappers (often incorrectly called thunks) or with an
        LK> adjustment field in the vtbl. -John]

If thunks are not merely function wrappers, what are they? closures?

(I really wish there was a "programming tricks" web page that
described things like trampolines, thunks, continuations, etc., both
from users' and from implementers' perspectives.)

[Thunks are call-by-name procedure arguments, which means they're
pretty close to closures. Consider this Algol 60 procedure known as
Jensen's device (give or take syntax details, it's been a while):

procedure J(X, I, U) begin
real J, X;
integer I, U;

J = 0.0;
for I := 1 to U do
J = J + X;

Looks like a slow way to multiply X * U, right? Nope, because Algol60
uses call-by-name which means that each procedure argument is
re-evaluated each time it's referenced:

real A[1:10];
integer N;

... = J(A[N]*A[N], N, 10);

This call to J does a sum of squares of A[], since A[N]*A[N] is
re-evaluated inside the procedure each time, and N is bound to I which
steps through the array.

To make this work, each actual procedure argument has to be a little
routine which evaluates the argument expression in the environment of
the caller. That's what a thunk is. To make life more exciting,
thunks also have to be storable, i.e., the thunk for the second
argument has to be able to store values into N.

Alan Perlis, who was on the Algol60 committee, told me that
call-by-name was a mistake; they were trying to define
call-by-reference in a clean way and were surprised when Jensen
pointed out later what they'd done. But it certainly forced people to
understand stack allocation of data a lot better than they had before.

The things that Microsoft calls thunks are usually called glue code,
if they do some setup fiddles jump to the routine, or function
wrappers if they interpose a layer of call between the caller and
callee. They're fine techniques, but they're not thunks. -John]

Post a followup to this message

Return to the comp.compilers page.
Search the comp.compilers archives again.