Reputation: 73
here is the problem I want to sumbit to you fellow gifted coders : I have a custom web container written in C++ that can communicate with javascript. From C++ to JS it can do synchronous JS function calls From JS to C++ it can do asynchronous C++ function calls
With these tools, I have to do a synchronous call from JS to C++... As I can't use message communication system (because it implies asynchronicity on the main thread unless I miss something), my first guess was to use worker thread
"main.js" file
var synctools = false;
var syncdata ="";
var myworker=new worker("demo_workers.js");
while(synctool == false){} //It s ugly but i haven t had any other ideas
"demo_workers.js" file
CallCPPFile(param,callback); //call the c++ and c++ call callback when finished
function callback(data)
{
//do stuff
syncdata = data;
synctools = true; //this is supposed to stop the looping of the main js
}
Unfortunatly, synctools and syncdata are not accessible from the worker thread. So here are a few questions :
Thanks for your help
Upvotes: 0
Views: 430
Reputation: 938
Here's the nuts and bolts of your problem. Synchronization in an asynchronous system requires both sides to cooperate. Your problem is that a piece of code running in complete isolation cannot have any of it's data updated unless it does this itself. Since all JavaScript threads are completely isolated from each other, unless you write some kind of external callable that can do the waiting for you, then you're stuck. There is no purely JavaScript solution to this problem.
If, however you don't mind writing some more C++, then you can do something clumsy and get something working:
Create a multi-threaded mini html server. Design the server to take an id (provided by the caller) as a parameter, create a storage point for data and wait. Design the server to take an id and data as parameters. When receiving a data parameter, the storage point associated with the received id is set and the wait associated with the id is removed.
This lets 1 javascript thread wait on another thread with a synchronous AJAX request. The only requirement is that the waiting thread use postMessage to send the wait id to the destination thread before waiting.
On second thought, something like this could also be done in pure javascript as long as you can create an http server in a separate thread. The trick would be keeping the http connection open until the response is ready. It all depends on what kind of JavaScript environment you're working in.
Upvotes: 0