Skip to content
Snippets Groups Projects
ScheduleOnTest.cpp 1.15 KiB
// SPDX-License-Identifier: LGPL-3.0-or-later
// Copyright © 2021 Florian Fischer
#include <chrono>
#include <thread>

#include "CountingPrivateSemaphore.hpp"
#include "Emper.hpp"
#include "Fiber.hpp"
#include "Runtime.hpp"
#include "Worker.hpp"
#include "emper.hpp"
#include "fixtures/assert.hpp"

static const unsigned ITERATIONS = 100;
static Runtime* runtime;
static unsigned workerCount;
unsigned iteration = 0;

static void runOn(CPS& cps) {
	ASSERT(Worker::getCurrentWorkerId() == (iteration % workerCount));
	++iteration;
	if (iteration == ITERATIONS) cps.signalAndExit();

	runtime->scheduleOn(*Fiber::from([&] { runOn(cps); }), (iteration % workerCount));
}

static void scheduleOnTest() {
	runtime = Runtime::getRuntime();
	ASSERT(runtime);
	workerCount = runtime->getWorkerCount();

	// Wait so all workers can suspend themselves
	if constexpr (emper::IO) {
		emper::sleep(1);
	} else {	// We can not sleep using emper mechanisms -> block the worker thread
		std::this_thread::sleep_for(std::chrono::seconds(1));
	}

	CPS cps(1);
	runtime->scheduleOn(*Fiber::from([&] { runOn(cps); }), (iteration % workerCount));
	cps.wait();
}

void emperTest() { scheduleOnTest(); }