Skip to content

Synchronous xhr requests running in a thread cause a deadlock #8117

@VirtualTim

Description

@VirtualTim

Using the Emscripten Fetch API, or xhr directly both cause a deadlock when run in synchronous mode in a thread.

Example code:

void fetch_xhr() {
  EM_ASM_({
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://emscripten.org/_static/Emscripten_logo_full.png', false);
    xhr.send();
    console.log("state:" + xhr.readyState + ", status:" + xhr.status);
  });
}

void fetch_emsc() {
  emscripten_fetch_attr_t attr;
  emscripten_fetch_attr_init(&attr);
  strcpy(attr.requestMethod, "GET");
  attr.attributes = EMSCRIPTEN_FETCH_LOAD_TO_MEMORY | EMSCRIPTEN_FETCH_SYNCHRONOUS;
  emscripten_fetch_t *fetch = emscripten_fetch(&attr, "https://emscripten.org/_static/Emscripten_logo_full.png");
  std::cout << "status: " << fetch->status << std::endl;
  emscripten_fetch_close(fetch);
}

int main(int argc, char** argv) {
  //auto t1 = std::thread(fetch_emsc);         //┐ swap these two
  auto t1 = std::thread(fetch_xhr);            //┘
  t1.join();                                   //<--hang here
  std::cout << "threads joined" << std::endl;

  return EXIT_SUCCESS;
}

Compile like: emcc test.cpp -s WASM=0 -s USE_PTHREADS=1 -s PTHREAD_POOL_SIZE=4 -s FETCH=1 -std=c++11 -o test.html

Execution seems to be stuck in the following area:

_emscripten_current_thread_process_queued_calls
_emscripten_main_thread_process_queued_calls
asm._emscripten_main_thread_process_queued_calls
_emscripten_futex_wait
_pthread_join
__ZNSt3__26thread4joinEv
_main

This seems a bit odd to me, as I would have thought you could perform an xhr from a non-main thread without any interaction from the main thread (unless you need to write to IndexedDB).

Any thoughts? Basically my end goal is to have a thread pause execution until a remote resource is downloaded. Unfortunately I can't use callbacks/promises here without a major rewrite of some old C++.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions