#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <pthread.h>
#include <sched.h>

#define NTHREADS 3

static pthread_rwlock_t rwlock;
static int dummy = 0;

static void *
worker(void *arg)
{
	int id = (intptr_t)arg;
	printf("Thread %d\n", id);
	unsigned seed = id;

	for (int i=0; i<1000; i++) {
		if (rand_r(&seed) & 3)
			pthread_rwlock_rdlock(&rwlock), seed += dummy;
		else
			dummy += pthread_rwlock_wrlock(&rwlock);
		sched_yield();
		pthread_rwlock_unlock(&rwlock);
	}
	printf("Finished %d\n", id);

	return NULL;
}

int main()
{
	pthread_t th[NTHREADS];
	pthread_rwlock_init(&rwlock, 0);

	for (int i = 0; i < NTHREADS; i++)
		pthread_create(&th[i], NULL, worker, (void *)(intptr_t)i);

	for (int i = 0; i < NTHREADS; i++)
		pthread_join(th[i], NULL);

	pthread_rwlock_destroy(&rwlock);
	return 0;
}
