Thunk
|
A thunk is a computer programming technique for resolving late binding of items. The essence of a thunk is to use a place holder to stand as a proxy until the last possible moment before using an item with the executable code. A thunk is a technique to cross that bridge when we come to it.
Contents |
Examples of use
Call by name
The call-by-name calling convention passes the name of the actual parameter to a function call. Where call-by-reference resolves the actual parameter's contents by a pointer or reference object. Call-by-name resolves to the actual object to the name of the item. The name of any actual parameter can only be known at run-time. Just as the pointer value of any actual parameter is unknown at run-time with call-by-reference.
To use a thunk, the compiler marks a spot for a reference to the named thing at runtime to achieve late binding. Call-by-name uses the lexographical significance of parameters in the call stack. Using a thunk allows late binding of a function invocation with the stack history at runtime.
When the function comes to an unknown parameter during execution, the thunk is fired to resolve the this-call-Name-of the actual parameter. While this sounds odd, in practice it normally only means adding to the most recent stack-frame.
Earlier use of thunk techniques were the working Algol 60 implementations. See also: B5000
Virtual memory paging
The essense of a virtual memory management system is that there is more memory allowed to be in-use by a program than actually exists physically. Typically virtual memory systems use a thunk to allocate empty pages from a free-page pool. Late binding in this way means that no free-pages need to be unnecessarily pre-committed. Memory is allocated only when the first used, not before.
OS/2 & Windows 16-bit address hack
A piece of code is executed to provide an address. The most common usage is in the Win16 / Win32 API, where thunking is used to convert a 16 bit address into a 32 bit equivalent or vice versa. The ubiquitous early example was "wsock32.dll", a thunking layer added to allow Win32 Internet applications to use the Win16 winsock.dll library originally written for Windows 3.11. Similar thunking was required in many cases in OS/2 2.x—while most of the operating system was 32-bit, many parts of the kernel and device drivers were 16-bit for compatibility reasons.
Thunk (Lisp)
In Lisp terminology, a thunk is a nullary function—one that takes no arguments. Thunks are frequently passed as arguments to functions. In Common Lisp, constant-valued thunks are created with the constantly
function: (constantly 5)
evaluates to a nullary function that, when called, always yields the value 5.