From c43fc8128deaf8c302737d23023440943ff749cc Mon Sep 17 00:00:00 2001 From: Kaushik Iska Date: Fri, 4 Jun 2021 17:37:21 -0500 Subject: [PATCH] Wait for the native callbacks from the spawned isolate (flutter/engine#26593) I think the problem here is that `Dart_InitializeIsolateCallback` which sets the message handler for the spawned/child isolate isn't guaranteed to be called from the same thread as the parent isolate. This is resulting in the following case: ``` void child(String message) { print('Child isolate got message: ' + message); notifyNative(); } void main() { Isolate.spawn(child, 'Hello from main isolate.'); notifyNative(); } ``` The `main` isolate could spawn a child and if we were to kill the main isolate before the native notifications were waited for, we could end up in a bad place. The ideal solution would be to guarantee that isolate shutdown ensures that all the spawned/child isolates are shutdown before shutting down the main isolate. --- engine/src/flutter/shell/common/shell_unittests.cc | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/engine/src/flutter/shell/common/shell_unittests.cc b/engine/src/flutter/shell/common/shell_unittests.cc index 4c5090f34d..2e90515b80 100644 --- a/engine/src/flutter/shell/common/shell_unittests.cc +++ b/engine/src/flutter/shell/common/shell_unittests.cc @@ -2485,10 +2485,12 @@ TEST_F(ShellTest, Spawn) { main_latch.Signal(); })); // Fulfill native function for the second Shell's entrypoint. + fml::CountDownLatch second_latch(2); AddNativeCallback( // The Dart native function names aren't very consistent but this is just // the native function name of the second vm entrypoint in the fixture. - "NotifyNative", CREATE_NATIVE_ENTRY([&](auto args) {})); + "NotifyNative", + CREATE_NATIVE_ENTRY([&](auto args) { second_latch.CountDown(); })); RunEngine(shell.get(), std::move(configuration)); main_latch.Wait(); @@ -2498,7 +2500,7 @@ TEST_F(ShellTest, Spawn) { PostSync( shell->GetTaskRunners().GetPlatformTaskRunner(), - [this, &spawner = shell, &second_configuration]() { + [this, &spawner = shell, &second_configuration, &second_latch]() { MockPlatformViewDelegate platform_view_delegate; auto spawn = spawner->Spawn( std::move(second_configuration), @@ -2541,6 +2543,11 @@ TEST_F(ShellTest, Spawn) { ASSERT_EQ(spawner->GetIOManager()->GetResourceContext().get(), spawn->GetIOManager()->GetResourceContext().get()); }); + + // Before destroying the shell, wait for expectations of the spawned + // isolate to be met. + second_latch.Wait(); + DestroyShell(std::move(spawn)); });