Less of a programming question, and more of an oddity that I'm seeking clarification on. Consider the following C program:
#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
volatile int counter = 0;
void incrementCounter()
{
counter += 1;
}
void* threadfunc()
{
for (int i = 0; i < 1000; i++)
{
incrementCounter();
}
}
int main()
{
pthread_t tids[100];
printf("Creating Threads...\n");
for (int i = 0; i < 100; i++)
{
pthread_create(&tids[i], NULL, threadfunc, NULL);
}
printf("Joining Threads...\n");
for (int i = 0; i < 100; i++)
{
pthread_join(tids[i], NULL);
}
printf("Finished. Counter = %d\n", counter);
}
This was what I wrote for a college assignment. Its supposed to show the dangers of multiple threads not locking when writing to variables.
I'm on Windows 10, so I open up my installation of Ubuntu Bash, and run
$ gcc -std=c99 -pthread main.c
$ ./a.out
It prints
Creating Threads...
Joining threads...
Finished. Counter = 100000
Ok... that's correct. It shouldn't be correct. This is supposed to be broken!
I run it again and again with the same results. Counter = 100000
each and every time! This may be the only time in my life that I'm disappointed my code works correctly.
So I log onto my schools shared Linux system for CS students. Pull my code, execute it the same way and I get:
Creating Threads...
Joining threads...
Finished. Counter = 99234
Next time, Counter = 99900
, then Counter = 100000
, then Counter = 99082
That's what I was expecting!
So my question:
What gives? What is it about the Linux Subsystem for Windows that causes my code not to break?