Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -504,9 +504,11 @@ void RuntimeScheduler_Modern::handleTaskError(
}

void RuntimeScheduler_Modern::clearQueues() {
// Destroyed after the lock is released: task destructors may schedule work.
decltype(taskQueue_) drainedTasks;
{
std::unique_lock lock(schedulingMutex_);
taskQueue_ = {};
drainedTasks.swap(taskQueue_);
isEventLoopScheduled_ = false;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -946,6 +946,48 @@ TEST_P(RuntimeSchedulerTest, clearsQueuesOnError) {
EXPECT_EQ(stubErrorUtils_->getReportFatalCallCount(), 1);
}

TEST_P(RuntimeSchedulerTest, clearQueuesAllowsTaskDestructorsToScheduleTasks) {
// Only for event loop
if (!GetParam()) {
return;
}

bool didRunScheduledFromDestructor = false;

auto scheduleTask = [&]() {
runtimeScheduler_->scheduleTask(
SchedulerPriority::NormalPriority, [&](jsi::Runtime& /*runtime*/) {
didRunScheduledFromDestructor = true;
});
};
// Schedules a task when it is destroyed.
auto scheduleOnDestroy =
std::make_shared<OnScopeExit<decltype(scheduleTask)>>(
std::move(scheduleTask));

auto throwingCallback =
createHostFunctionFromLambda([&](bool /*unused*/) -> jsi::Value {
throw jsi::JSError(*runtime_, "Test error");
});

runtimeScheduler_->scheduleTask(
SchedulerPriority::ImmediatePriority, std::move(throwingCallback));
runtimeScheduler_->scheduleTask(
SchedulerPriority::LowPriority,
[scheduleOnDestroy =
std::move(scheduleOnDestroy)](jsi::Runtime& /*runtime*/) {});

EXPECT_EQ(stubQueue_->size(), 1);

// The throwing task clears the queues, which destroys the low priority task
// and runs its capture's destructor. That must not deadlock, and the task it
// schedules must still run.
stubQueue_->tick();

EXPECT_TRUE(didRunScheduledFromDestructor);
EXPECT_EQ(stubErrorUtils_->getReportFatalCallCount(), 1);
}

TEST_P(RuntimeSchedulerTest, basicSameThreadExecution) {
bool didRunSynchronousTask = false;
std::thread t1([this, &didRunSynchronousTask]() {
Expand Down
Loading