Callback (computer programming)

Uses your system voice; voice and rate in settings.

Snapshot

≈ 8 min read

Names in other languages

No names in other languages are held for this entry yet.

Article bodies are English and are not machine-translated. A name in another language is not a translation of the article.

In computer programming, a callback is a programming pattern in which a function reference is passed from one context (consumer) to another (provider) such that the provider can call the function. If the function accesses state or functionality of the consumer, then the call is back to the consumer – backwards compared to the normal flow of control in which a consumer calls a provider. A function that accepts a callback parameter may be designed to call back before returning to its caller. But, more typically, a callback reference is stored by the provider so that it can call the function later (as deferred). If the provider invokes the callback on the same thread as the consumer, then the call is blocking, a.k.a. synchronous. If instead, the provider invokes the callback on a different thread, then the call is non-blocking, a.k.a. asynchronous. A callback can be likened to leaving instructions with a tailor for what to do when a suit is ready, such as calling a specific phone number or delivering it to a given address. These instructions represent a callback: a function provided in advance to be executed later, often by a different part of the system and not necessarily by the one that received it. The difference between a general function reference and a callback can be subtle, and some use the terms interchangeably but distinction generally depends on programming intent.…

In computer programming, a callback is a programming pattern in which a function reference is passed from one context (consumer) to another (provider) such that the provider can call the function. If the function accesses state or functionality of the consumer, then the call is back to the consumer – backwards compared to the normal flow of control in which a consumer calls a provider. A function that accepts a callback parameter may be designed to call back before returning to its caller. But, more typically, a callback reference is stored by the provider so that it can call the function later (as deferred). If the provider invokes the callback on the same thread as the consumer, then the call is blocking, a.k.a. synchronous. If instead, the provider invokes the callback on a different thread, then the call is non-blocking, a.k.a. asynchronous. A callback can be likened to leaving instructions with a tailor for what to do when a suit is ready, such as calling a specific phone number or delivering it to a given address. These instructions represent a callback: a function provided in advance to be executed later, often by a different part of the system and not necessarily by the one that received it. The difference between a general function reference and a callback can be subtle, and some use the terms interchangeably but distinction generally depends on programming intent. If the intent is like the telephone callback that the original called party communicates back to the original caller then it's a callback. == Use == A blocking callback runs in the execution context of the function that passes the callback. A deferred callback can run in a different context such as during interrupt or from a thread. As such, a deferred callback can be used for synchronization and delegating work to another thread. from typing import Callable def write_status(message: str) -> None: write(stdout, message) def write_error(message: str) -> None: write(stderr, message) def say_hi(write: Callable[[str], None]) -> None: write("Hello world") ==Example code== include include include include struct Data { // ... }; static struct Data data = { // initialize contents here }; static volatile sigatomic_t flag = 0; void cleanupHandler(int signum) { flag = 1; int saveFile = open("savefile.dat", O_WRONLY | O_CREATO, S_IWUSR); write(saveFile, data, sizeof data); close(saveFile); } int main(void) { signal(cleanupHandler, SIGTERM); doStuff(); } Another common use for callbacks in C is with C standard library functions used for sorting ( qsort() ) and searching ( lsearch() , bsearch() ) where a comparator function is passed as an argument to the routine to determine the collation order. include struct Person { char name[20]; int age; }; Person people[1000]; // Collates people by age int compareAges(struct Person* p1, struct Person* p2) { return p2->age - p1->age; } int main(void) { // ... int numberOfPeople = /* some number here */; qsort(numberOfPeople, sizeof (struct Person), people, compareAges); // ... } Callbacks may also be used to control whether a function acts or not: Xlib allows custom predicates to be specified to determine whether a program wishes to handle an event. In the following C code, function printNumber() uses parameter getNumber as a blocking callback. printNumber() is called with getAnswerToMostImportantQuestion() which acts as a callback function. When run, the answer to the question is: "Value: 42". include include void printNumber(int (*getNumber)(void)) { int val = getNumber(); printf("Value: %d\n", val); } int getAnswerToMostImportantQuestion(void) { return 42; } int main(void) { printNumber(getAnswerToMostImportantQuestion); return 0; } import std; class MyCallback { public: void operator()(int x) { std::println("Callback called with value: {}", x); } }; template void performOperation(int a, Callback callback) { std::println("Performing operation on: {}", a); callback(a); } int main() { MyCallback callback; int value = 10; performOperation(value, callback); return 0; } std::function is a type-erased wrapper for any callable objects, introduced in C++11: import std; using std::function; void performOperation(int a, function callback) { std::println("Performing operation on: {}", a); callback(a); } int main() { int value = 10; performOperation(value, [](int x) -> void { std::println("Callback called with value: {}", x); }); return 0; } namespace Wikipedia.Examples; using System; class Helper { public void PerformAction(Action callback) { callback("Hello world"); } } public class Main { static void Log(string str) { Console.WriteLine($"Callback was: {str}"); } static void Main(string[] args) { Helper helper = new(); helper.PerformAction(Log); } } function calculate(a, b, operate) { return operate(a, b); } function multiply(a, b) { return a * b; } function sum(a, b) { return a + b; } // outputs 20 alert(calculate(10, 2, multiply)); // outputs 12 alert(calculate(10, 2, sum)); The collection method of the jQuery library uses the function passed to it as a blocking callback. It calls the callback for each item of the collection. For example: $("li").each(function(index) { console.log(index + ": " + $(this).text()); }); Deferred callbacks are commonly used for handling events from the user, the client and timers. Examples can be found in , Ajax and XMLHttpRequest . In addition to using callbacks in JavaScript source code, C functions that take a function are supported via js-ctypes. julia> square(val) = val^2 square (generic function with 1 method) julia> calculate(operate, val) = operate(val) calculate (generic function with 1 method) julia> calculate(square, 5) 25 fun main() { print("Enter the most important question: ") val question = readLine() askAndAnswer(question, ::getAnswerToMostImportantQuestion) } fun getAnswerToMostImportantQuestion(): Int { return 42 } fun askAndAnswer(question: String?, getAnswer: () -> Int) { println("Question: $question") println("Answer: ${getAnswer()}") } function calculate(a, b, operation) return operation(a, b) end function multiply(a, b) return a * b end function add(a, b) return a + b end print(calculate(10, 20, multiply)) -- outputs 200 print(calculate(10, 20, add)) -- outputs 30 -- an example of a callback using an anonymous function print(calculate(10, 20, function(a, b) return a / b -- outputs 0.5 end)) ===Python=== In the following Python code, function accepts a parameter that is used as a blocking callback. is called with which acts as a callback function. def square(val: int) -> int: return val ** 2 def calculate(operate: Callable[[int], int], val: int) -> int: return operate(val) prints: 25 print(calculate(square, 5)) Red [Title: "Callback example"] calculate: func [ num1 [number!] num2 [number!] callback-function [function!] ][ callback-function num1 num2 ] calc-product: func [ num1 [number!] num2 [number!] ][ num1 * num2 ] calc-sum: func [ num1 [number!] num2 [number!] ][ num1 + num2 ] alerts 75, the product of 5 and 15 alert form calculate 5 15 :calc-product alerts 20, the sum of 5 and 15 alert form calculate 5 15 :calc-sum fn call_with_one (func: F) -> usize where F: Fn(usize) -> usize { func(1) } let double = |x| x * 2; assert_eq!(call_with_one(double), 2);

Text derived from https://en.wikipedia.org/w/index.php?oldid=1370775388 under CC BY-SA 4.0; modifications have been made.