Howto:Start worker threads using listeners in Nasal: Difference between revisions

From FlightGear wiki
Jump to navigation Jump to search
mNo edit summary
m (<syntaxhighlight lang="php">)
Line 3: Line 3:
Once invoked, the hello function keeps calling itself asynchronously using a settimer() call at an interval of 5 seconds. After 60 seconds, it is getting terminated by the second listener that registered the "kill_thread" handler to be invoked by settimer after 60 seconds, via another Nasal thread.
Once invoked, the hello function keeps calling itself asynchronously using a settimer() call at an interval of 5 seconds. After 60 seconds, it is getting terminated by the second listener that registered the "kill_thread" handler to be invoked by settimer after 60 seconds, via another Nasal thread.


<syntaxhighlight lang="php">
  # async_demo.nas
  # async_demo.nas
  var cancel_thread=0;
  var cancel_thread=0;
Line 27: Line 28:
   print("async_demo.nas loaded");
   print("async_demo.nas loaded");
  });
  });
</syntaxhighlight>
   
   
To run the demo, copy/paste the code to a file in $FG_ROOT/Nasal, start up fgfs and modify the property "/nasal-threading/test" using the built-in property browser.
To run the demo, copy/paste the code to a file in $FG_ROOT/Nasal, start up fgfs and modify the property "/nasal-threading/test" using the built-in property browser.

Revision as of 21:07, 5 January 2012

The following snippet of code demonstrates how to run a Nasal function (named "hello") in a dedicated background thread (i.e. asynchronously) once a property listener is fired.

Once invoked, the hello function keeps calling itself asynchronously using a settimer() call at an interval of 5 seconds. After 60 seconds, it is getting terminated by the second listener that registered the "kill_thread" handler to be invoked by settimer after 60 seconds, via another Nasal thread.

 # async_demo.nas
 var cancel_thread=0;
 var l = nil;
 var r = nil;
 
 var hello = func {
   print("Hello world from the background thread\n");
   if(!cancel_thread) settimer(hello,5,1);
 }
 var spawn = func(c) return func {thread.newthread(c)};
 var setlistener_job = func(p,f) setlistener(p, spawn(f) );
 
 var kill_thread = func {
   removelistener(l);
   print("Killing background thread");
   cancel_thread=1;
   removelistener(r);
 }
 
 _setlistener("/sim/signals/nasal-dir-initialized", func {
  l=setlistener_job("/nasal-threading/test", hello);
  r=setlistener_job("/nasal-threading/test", func { settimer(kill_thread, 60, 1); });
  print("async_demo.nas loaded");
 });

To run the demo, copy/paste the code to a file in $FG_ROOT/Nasal, start up fgfs and modify the property "/nasal-threading/test" using the built-in property browser.