Skip to content

Commit 1f1a5ed

Browse files
committed
Улучшенная функция thread
1 parent 1f6a17a commit 1f1a5ed

File tree

2 files changed

+25
-6
lines changed

2 files changed

+25
-6
lines changed

program.own

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,4 +111,9 @@ println typeof({})
111111
println typeof(add)
112112

113113
println typeof(number("1"))
114-
println typeof(string(1))
114+
println typeof(string(1))
115+
116+
thread(::inthread)
117+
def inthread() = echo("this is a thread")
118+
thread(def (str) { println str }, "this is a thread with arguments")
119+
Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,34 @@
11
package com.annimon.ownlang.lib.modules.functions;
22

33
import com.annimon.ownlang.lib.Function;
4+
import com.annimon.ownlang.lib.FunctionValue;
45
import com.annimon.ownlang.lib.Functions;
56
import com.annimon.ownlang.lib.NumberValue;
7+
import com.annimon.ownlang.lib.Types;
68
import com.annimon.ownlang.lib.Value;
79

810
public final class std_thread implements Function {
911

1012
@Override
1113
public Value execute(Value... args) {
12-
if (args.length == 1) {
13-
// Создаём новый поток по имени функции
14-
new Thread(() -> {
15-
Functions.get(args[0].asString()).execute();
16-
}).start();
14+
// Создаём новый поток и передаём параметры, если есть.
15+
// Функция может передаваться как напрямую, так и по имени
16+
if (args.length == 0) throw new RuntimeException("At least one arg expected");
17+
18+
Function body;
19+
if (args[0].type() == Types.FUNCTION) {
20+
body = ((FunctionValue) args[0]).getValue();
21+
} else {
22+
body = Functions.get(args[0].asString());
1723
}
24+
25+
// Сдвигаем аргументы
26+
final Value[] params = new Value[args.length - 1];
27+
if (params.length > 0) {
28+
System.arraycopy(args, 1, params, 0, params.length);
29+
}
30+
31+
new Thread(() -> body.execute(params)).start();
1832
return NumberValue.ZERO;
1933
}
2034
}

0 commit comments

Comments
 (0)