// SPDX-License-Identifier: LGPL-3.0-or-later
// Copyright © 2021 Florian Fischer
#include "BinaryPrivateSemaphore.hpp"
#include "CountingPrivateSemaphore.hpp"
#include "Debug.hpp"
#include "emper-config.h"
#include "emper.hpp"

static BPS* sems;

static const unsigned CYCLE_LENGTH = 3;
static const unsigned CYCLE_COUNT = 100;
static const unsigned ITERATIONS = EMPER_LOG_LEVEL > Info ? 100 : 25000;

void emperTest() {
	CPS cps;
	const unsigned count = CYCLE_COUNT * CYCLE_LENGTH;
	sems = new BPS[count];
	for (unsigned i = 0; i < count; ++i) {
		spawn(
				[=] {
					const unsigned cycleNum = i / CYCLE_LENGTH;
					const unsigned cycleStart = CYCLE_LENGTH * cycleNum;
					BPS& mySem = sems[i];
					const unsigned next = cycleStart + ((i + 1) % CYCLE_LENGTH);
					BPS& nextSem = sems[next];

					for (unsigned it = 0; it < ITERATIONS; ++it) {
						if (i == cycleStart) nextSem.signal();

						mySem.wait();
						mySem.reset();

						if (i != cycleStart) nextSem.signal();
					}
				},
				cps);
	}

	cps.wait();

	delete[] sems;
}