Brain Dump

Race Condition

Tags
comp-sci

Is a bug in multi-threaded programs where the outcome of some code is determined by the processor. I.E. It's inconsistent (non-deterministic) from one run to the next.

void *thread_main(void *p) {
    int *p_int = (int*) p;
    int x = *p_int;
    x += x;
    *p_int = x;
    return NULL;
}

int main() {
    int data = 1;
    pthread_t one, two;
    pthread_create(&one, NULL, thread_main, &data);
    pthread_create(&two, NULL, thread_main, &data);
    pthread_join(one, NULL);
    pthread_join(two, NULL);
    printf("%d\n", data);
    return 0;
}
Code Snippet 1: The canonical race condition example. In the time one thread fetches, increments, and writes the value pointed to by *p, another thread could've already done so or do so out of order leading to only one increment or both increments depending on how the CPU acts.