Explore Library
Code Quiz

TurboModule Callback Threading Bug

A C++ TurboModule invokes a JS callback from a background thread and crashes — spot why.

Codecpp
// C++ TurboModule method exposed via JSI
void NativeFileModule::readFile(jsi::Runtime &rt, jsi::String path, jsi::Function callback) {
  auto cb = std::make_shared<jsi::Function>(std::move(callback));
  std::string p = path.utf8(rt);

  // Do blocking I/O off the JS thread
  std::thread([this, &rt, cb, p]() {
    std::string contents = performBlockingRead(p); // heavy work

    // Deliver the result back to JavaScript
    cb->call(rt, jsi::String::createFromUtf8(rt, contents));
  }).detach();
}

This module intermittently crashes with heap corruption or a runtime assertion. What is the bug?