#include <stdlib.h>
#include <stdio.h>
#include <semaphore.h>
#include "lwt.h"

typedef struct
{
	sem_t *prev;
	sem_t *next;
	int id;
} ThreadData;

static const int numThreads = 100;
static volatile int token = 0;

static void ring(void *td, void *unused)
{
	(void)unused;

	ThreadData *data = (ThreadData*)td;
	const int myid = data->id;

	if(myid != (numThreads - 1)) {
		sem_wait(data->prev);
	}

	token += 1;
	sem_post(data->next);
}

int main()
{
	if(lwt_init() != 0) {
		return EXIT_FAILURE;
	}

	sem_t sems[numThreads];
	ThreadData tdata[numThreads];

	for(int i = 0; i < numThreads; ++i) {
		sem_init(&sems[i], 0, 0);
		if(i == 0) {
			tdata[i].prev = &sems[numThreads-1];
		}
		else {
			tdata[i].prev = &sems[i-1];
		}

		tdata[i].next = &sems[i];
		tdata[i].id = i;
	}

	for(int i = 0; i < numThreads; ++i) {
		lwt_run(ring, (void*)(&tdata[i]), 0);
	}

	lwt_destroy();

	printf("token == %d\n", token);

	return EXIT_SUCCESS;
}
