/*
 * Volatile example: the reader accesses the shared state through a
 * volatile pointer, so the compiler has to load 'done' in every
 * iteration of the loop.
 *
 * Note: volatile only affects the compiler. It does not emit any
 * barrier instructions, so the CPU can still reorder the accesses.
 */

#include <assert.h>
#include <stdbool.h>

/* Stand-in for PostgreSQL's Assert() macro */
#define Assert(condition) assert(condition)

typedef struct SharedState
{
    int  tuples;
    bool done;
} SharedState;

/* Executed by CPU 1, 'shared' points to shared memory */
void writer(SharedState *shared, int pages, int tuples_per_page)
{
    shared->tuples = pages * tuples_per_page;
    shared->done = true;
}

/* Executed by CPU 2, 'shared' points to shared memory */
void reader(volatile SharedState *shared)
{
    while (!shared->done)
        /* Wait for the writer to finish */;

    Assert(shared->tuples != 0);
}
