Mercurial Hosting > luan
diff src/luan/lib/ThreadLib.java @ 126:0149bdf98fd8
add ThreadLib
git-svn-id: https://luan-java.googlecode.com/svn/trunk@127 21e917c8-12df-6dd8-5cb6-c86387c605b9
author | fschmidt@gmail.com <fschmidt@gmail.com@21e917c8-12df-6dd8-5cb6-c86387c605b9> |
---|---|
date | Fri, 06 Jun 2014 14:16:38 +0000 |
parents | |
children | 0594c132888b |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/luan/lib/ThreadLib.java Fri Jun 06 14:16:38 2014 +0000 @@ -0,0 +1,51 @@ +package luan.lib; + +import java.util.concurrent.Executor; +import java.util.concurrent.Executors; +import luan.LuanState; +import luan.LuanFunction; +import luan.LuanTable; +import luan.LuanJavaFunction; +import luan.LuanException; +import luan.DeepCloner; + + +public final class ThreadLib { + + public static void load(LuanState luan) throws LuanException { + luan.load("Thread",LOADER); + } + + public static final LuanFunction LOADER = new LuanFunction() { + @Override public Object call(LuanState luan,Object[] args) { + LuanTable module = new LuanTable(); + try { + add( module, "fork", LuanState.class, LuanFunction.class, new Object[0].getClass() ); + } catch(NoSuchMethodException e) { + throw new RuntimeException(e); + } + return module; + } + }; + + private static void add(LuanTable t,String method,Class<?>... parameterTypes) throws NoSuchMethodException { + t.put( method, new LuanJavaFunction(ThreadLib.class.getMethod(method,parameterTypes),null) ); + } + + private static final Executor exec = Executors.newCachedThreadPool(); + + public static void fork(LuanState luan,LuanFunction fn,Object... args) { + DeepCloner cloner = new DeepCloner(); + final LuanState newLuan = cloner.deepClone(luan); + final LuanFunction newFn = cloner.get(fn); + final Object[] newArgs = cloner.deepClone(args); + exec.execute(new Runnable(){public void run() { + try { + newLuan.JAVA.call(newFn,"<forked>",newArgs); + } catch(LuanException e) { + e.printStackTrace(); + } + }}); + } + +}