Add peek to channels

This commit is contained in:
Ryan Ward 2023-07-02 10:52:10 -04:00
parent ef93c6a2a8
commit 98b86af488
2 changed files with 31 additions and 0 deletions

View File

@ -8,6 +8,7 @@ void Channel::exportAPI(sol::state_view& lua) {
sol::usertype<Channel> type("new", sol::no_constructor, sol::usertype<Channel> type("new", sol::no_constructor,
"push", &Channel::push, "push", &Channel::push,
"pop", &Channel::pop, "pop", &Channel::pop,
"peek", &Channel::peek,
"size", &Channel::size "size", &Channel::size
); );
sol::stack::push(lua, type); sol::stack::push(lua, type);
@ -84,6 +85,33 @@ StoredArray Channel::pop(const sol::optional<int>& duration,
return ret; return ret;
} }
StoredArray Channel::peek(const sol::optional<int>& duration,
const sol::optional<std::string>& period) {
this_thread::cancellationPoint();
std::unique_lock<std::mutex> lock(ctx_->lock_);
{
this_thread::ScopedSetInterruptable interruptable(this);
Timer timer(duration ? fromLuaTime(duration.value(), period) :
std::chrono::milliseconds());
while (ctx_->channel_.empty()) {
if (duration) {
if (timer.isFinished() ||
ctx_->cv_.wait_for(lock, timer.left()) ==
std::cv_status::timeout) {
return StoredArray();
}
}
else { // No time limit
ctx_->cv_.wait(lock);
}
this_thread::cancellationPoint();
}
}
return ctx_->channel_.front();
}
size_t Channel::size() { size_t Channel::size() {
std::lock_guard<std::mutex> lock(ctx_->lock_); std::lock_guard<std::mutex> lock(ctx_->lock_);
return ctx_->channel_.size(); return ctx_->channel_.size();

View File

@ -24,6 +24,9 @@ public:
bool push(const sol::variadic_args& args); bool push(const sol::variadic_args& args);
StoredArray pop(const sol::optional<int>& duration, StoredArray pop(const sol::optional<int>& duration,
const sol::optional<std::string>& period); const sol::optional<std::string>& period);
StoredArray peek(const sol::optional<int>& duration,
const sol::optional<std::string>& period);
size_t size(); size_t size();