Search code examples
c++firefoxnpapi

Sequence call to NPN_PluginThreadAsyncCall


In my plugin, I create a thread (using pthread in my case) to listen to external event. When event occurs, I want to communicate back to JavaScript. As far as I understand, I can only call NPN_* method in the plugin thread. As the result, I will need to utilize NPN_PluginThreadAsyncCall in my thread to call other NPN_* method for JavaScript communication. So a simple flow is

The problem I am facing now is, if the external occurs consecutively, for example, 2 events with different data input, I will receive the same data twice in the callback sometimes (in half of the time two different data is returned). I guess it's because the NPN_PluginThreadAsyncCall is an async call, when two consecutive events call back, NPN_PluginThreadAsyncCall is invoked twice, the data is overridden by the 2nd call already before callback to JavaScript for the 1st event actually occurs.

Initially, the event data I want to return is a global variable. But I also tried to change it to a local variable, it did not seem to help. Is there any other way I can make my code a sequential call to talk to JavaScript?

I have done some research and found this, How to callback plugin thread on Safari 5.1 on OSX?. But I still don't quite understand (I am working on Windows).


Solution

  • You could implement this as a mutexed std::deque, where the first inserted data is the first that you pop.

    Just make sure that you don't push or pop at the same time (use mutexes). That's what I use in my plugin :)