Улучшенная функция thread

This commit is contained in:
Victor 2016-01-09 14:54:06 +02:00
parent 1f6a17a024
commit 1f1a5ed7f0
2 changed files with 25 additions and 6 deletions

View File

@ -112,3 +112,8 @@ println typeof(add)
println typeof(number("1")) println typeof(number("1"))
println typeof(string(1)) println typeof(string(1))
thread(::inthread)
def inthread() = echo("this is a thread")
thread(def (str) { println str }, "this is a thread with arguments")

View File

@ -1,20 +1,34 @@
package com.annimon.ownlang.lib.modules.functions; package com.annimon.ownlang.lib.modules.functions;
import com.annimon.ownlang.lib.Function; import com.annimon.ownlang.lib.Function;
import com.annimon.ownlang.lib.FunctionValue;
import com.annimon.ownlang.lib.Functions; import com.annimon.ownlang.lib.Functions;
import com.annimon.ownlang.lib.NumberValue; import com.annimon.ownlang.lib.NumberValue;
import com.annimon.ownlang.lib.Types;
import com.annimon.ownlang.lib.Value; import com.annimon.ownlang.lib.Value;
public final class std_thread implements Function { public final class std_thread implements Function {
@Override @Override
public Value execute(Value... args) { public Value execute(Value... args) {
if (args.length == 1) { // Создаём новый поток и передаём параметры, если есть.
// Создаём новый поток по имени функции // Функция может передаваться как напрямую, так и по имени
new Thread(() -> { if (args.length == 0) throw new RuntimeException("At least one arg expected");
Functions.get(args[0].asString()).execute();
}).start(); Function body;
if (args[0].type() == Types.FUNCTION) {
body = ((FunctionValue) args[0]).getValue();
} else {
body = Functions.get(args[0].asString());
} }
// Сдвигаем аргументы
final Value[] params = new Value[args.length - 1];
if (params.length > 0) {
System.arraycopy(args, 1, params, 0, params.length);
}
new Thread(() -> body.execute(params)).start();
return NumberValue.ZERO; return NumberValue.ZERO;
} }
} }