#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <inttypes.h>
#include <assert.h>
#include <unistd.h>

volatile int64_t bank_balance; // the current balance of the bank account

void* ThreadMain(void *arg);
void die(char *);

int main(int argc, char *argv[]) {
	bank_balance = 0; // start with an empty account

	// create the first banking customer
	pthread_t customer1;
	int ret = pthread_create(&customer1, NULL, ThreadMain, NULL);
	if (ret != 0) die("pthread_create()");

	// create the second banking customer
	pthread_t customer2;
	ret = pthread_create(&customer2, NULL, ThreadMain, NULL);
	if (ret != 0) die("pthread_create()");

	// constantly print out the bank account balance
	for (;;) {
		int64_t cur_bal = bank_balance;
		printf("%" PRId64 "\n", cur_bal);
	}
}

void *ThreadMain(void *threadArgs) {
	pthread_detach(pthread_self());

	for (;;) {
		bank_balance++;
	}
}

void die(char *str)
{
	fprintf(stderr, "%s", str);
	fflush(stderr);
	exit(1);
}
