Event-driven programming is a programming paradigm where the flow of the program is determined by events—occurrences such as I/O completions, user interactions, or timer expirations. Code is structured around event handlers (callbacks) that execute asynchronously when their associated events occur.
void computeChecksum(char *buf, int blockNum, int numBytes) {
char xsum = 0;
for (int i = 0; i < numBytes; i++)
xsum ^= buf[i];
printf("Checksum: %d\n", xsum);
free(buf);
}
void checksumDiskData(int blockNum, int numBytes) {
char *buf = malloc(numBytes);
// Register handler and initiate read
diskRead(buf, blockNum, numBytes, computeChecksum);
// Function returns immediately; handler runs later
}
Event-driven code is inherently more difficult than sequential code:
Despite the difficulties, event-driven programming is necessary when dealing with asynchronous operations like I/O. The CPU can execute millions of instructions while waiting for a single disk read; event-driven code allows useful work during these waits.
Event-driven programming is common in: