Files
EchoionStandalone/tests/test_event_callback_gate.cpp
faumaray 45eb2cab42 Update
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-12 02:57:35 +03:00

60 lines
1.4 KiB
C++

#include "echoion/standalone/EventCallbackGate.hpp"
#include <atomic>
#include <cassert>
#include <chrono>
#include <condition_variable>
#include <future>
#include <memory>
#include <mutex>
int main()
{
Echoion::Standalone::EventCallbackGate gate;
std::mutex mutex;
std::condition_variable enteredCv;
std::condition_variable releaseCv;
bool entered = false;
bool release = false;
std::atomic<int> calls{0};
auto lifetime = std::make_shared<int>(42);
std::weak_ptr<int> observedLifetime = lifetime;
gate.add([&, lifetime](const Echoion::Api::PluginEvent&) {
++calls;
std::unique_lock lock(mutex);
entered = true;
enteredCv.notify_all();
releaseCv.wait(lock, [&] { return release; });
});
lifetime.reset();
Echoion::Api::PluginEvent event;
auto dispatch = std::async(std::launch::async, [&] { gate.dispatch(event); });
{
std::unique_lock lock(mutex);
enteredCv.wait(lock, [&] { return entered; });
}
auto quiesce = std::async(std::launch::async, [&] { gate.quiesce(); });
assert(quiesce.wait_for(std::chrono::milliseconds{30}) ==
std::future_status::timeout);
assert(!observedLifetime.expired());
{
std::lock_guard lock(mutex);
release = true;
}
releaseCv.notify_all();
dispatch.get();
quiesce.get();
assert(observedLifetime.expired());
gate.dispatch(event);
assert(calls == 1);
gate.add([&](const Echoion::Api::PluginEvent&) { ++calls; });
gate.dispatch(event);
assert(calls == 2);
}