Steve Klabnik

inception - The movie, explained through C code

I’ll be honest: this is one of the cooler things I’ve seen recently:

 * Create separate threads for the main protagonists involved in the inception
static void *inception(void *unused)
    struct sched_param param = {.sched_priority = 99 };
    int policy = SCHED_OTHER;
        output("Setting policy to real time processn");
        policy = SCHED_FIFO;
        param.sched_priority = 0;
    assert(pthread_setschedparam(pthread_self(), policy, &param) == 0);
    lucid_dreamer("Fischer", DREAM_INCEPTION_TARGET);
    lucid_dreamer("Cobb", DREAM_INCEPTION_PERFORMER);
    lucid_dreamer("Ariadne", DREAM_WORLD_ARCHITECT);
    lucid_dreamer("Arthur", DREAM_ORGANIZER);
    lucid_dreamer("Eames", DREAM_SHAPES_FAKER);
    lucid_dreamer("Yusuf", DREAM_SEDATIVE_CREATOR);
    lucid_dreamer("Saito", DREAM_OVERLOOKER);
    pthread_cond_wait(&inception_reality_wakeup_for_all, &inception_reality_mutex);
    return NULL;

That’s right: karthick18’s ‘inception’ repository contains a 1900 line C program that simulates the plot of the movie Inception. How, you ask?

We need to go deeper.

Have you heard of the Dining Philosopher’s problem? Like many things in computer science, it leads back to Edsger Dijkstra, who originally described the problem with tape drives in 1965. Here’s a summary:

Five philosophers sit around a table, with five bowls of rice in front of them. In between each bowl of rice is a chopstick. A philosopher can do two things: think and eat. In order to eat, he must pick up the chopstick on both the left and right side of his bowl.
dining philosophers

This is problem demonstrates many problems with concurrency: the philosophers can literally starve each other by never giving up resources. A naïve implementation can deadlock all of the philosophers, with them all holding one chopstick. Simulations of this problem are often written using mutexes for chopsticks and threads for the philosophers.

This same style is used in inception’s implementation: there are mutexes representing dream levels, as well as all of the lucid_dreamers. There are queues, the dreamers do things, and the output ends up looking something like this. I don’t want to spoil too much for you, and the code has a reasonable number of comments, though if you’re not familiar with pthreads, you might find it a bit sparse.

Totally cool.

The code on GitHub.


Sign in or Join to comment or subscribe

Player art
  0:00 / 0:00