Mercurial Hosting > luan
comparison 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 |
comparison
equal
deleted
inserted
replaced
125:0cd559a16758 | 126:0149bdf98fd8 |
---|---|
1 package luan.lib; | |
2 | |
3 import java.util.concurrent.Executor; | |
4 import java.util.concurrent.Executors; | |
5 import luan.LuanState; | |
6 import luan.LuanFunction; | |
7 import luan.LuanTable; | |
8 import luan.LuanJavaFunction; | |
9 import luan.LuanException; | |
10 import luan.DeepCloner; | |
11 | |
12 | |
13 public final class ThreadLib { | |
14 | |
15 public static void load(LuanState luan) throws LuanException { | |
16 luan.load("Thread",LOADER); | |
17 } | |
18 | |
19 public static final LuanFunction LOADER = new LuanFunction() { | |
20 @Override public Object call(LuanState luan,Object[] args) { | |
21 LuanTable module = new LuanTable(); | |
22 try { | |
23 add( module, "fork", LuanState.class, LuanFunction.class, new Object[0].getClass() ); | |
24 } catch(NoSuchMethodException e) { | |
25 throw new RuntimeException(e); | |
26 } | |
27 return module; | |
28 } | |
29 }; | |
30 | |
31 private static void add(LuanTable t,String method,Class<?>... parameterTypes) throws NoSuchMethodException { | |
32 t.put( method, new LuanJavaFunction(ThreadLib.class.getMethod(method,parameterTypes),null) ); | |
33 } | |
34 | |
35 private static final Executor exec = Executors.newCachedThreadPool(); | |
36 | |
37 public static void fork(LuanState luan,LuanFunction fn,Object... args) { | |
38 DeepCloner cloner = new DeepCloner(); | |
39 final LuanState newLuan = cloner.deepClone(luan); | |
40 final LuanFunction newFn = cloner.get(fn); | |
41 final Object[] newArgs = cloner.deepClone(args); | |
42 exec.execute(new Runnable(){public void run() { | |
43 try { | |
44 newLuan.JAVA.call(newFn,"<forked>",newArgs); | |
45 } catch(LuanException e) { | |
46 e.printStackTrace(); | |
47 } | |
48 }}); | |
49 } | |
50 | |
51 } |