Cache coherence is the guarantee that all cores see a single, consistent view of memory despite each core maintaining its own private cache. Without it, one core's write to a cached variable could be invisible to another core's read, violating fundamental correctness.
Coherence protocols fall into two families: snooping (broadcast on a shared bus) and directory-based (track sharers in a directory lookup). Coherence differs from consistency, which governs ordering of writes to different locations.
This example demonstrates cache coherence by writing and reading a shared variable across threads.
// compile: gcc -std=c11 -pthread -o coherence coherence.c // run: ./coherence // description: show cache coherence maintaining visibility across cores #include <stdio.h> #include <pthread.h> #include <stdatomic.h> #include <unistd.h> atomic_int x = 0; void* writer_thread(void* arg) { sleep(1); atomic_store(&x, 42); printf("Writer: wrote x = 42\n"); return NULL; } void* reader_thread(void* arg) { for (int i = 0; i < 10; i++) { int val = atomic_load(&x); if (val == 42) { printf("Reader: saw x = 42\n"); return NULL; } usleep(100000); } return NULL; } int main() { pthread_t writer, reader; pthread_create(&writer, NULL, writer_thread, NULL); pthread_create(&reader, NULL, reader_thread, NULL); pthread_join(writer, NULL); pthread_join(reader, NULL); return 0; }