diff --git a/src/com/annimon/ownlang/lib/modules/functions/std_sync.java b/src/com/annimon/ownlang/lib/modules/functions/std_sync.java new file mode 100644 index 0000000..0dd01c8 --- /dev/null +++ b/src/com/annimon/ownlang/lib/modules/functions/std_sync.java @@ -0,0 +1,36 @@ +package com.annimon.ownlang.lib.modules.functions; + +import com.annimon.ownlang.exceptions.TypeException; +import com.annimon.ownlang.lib.*; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; + +public final class std_sync implements Function { + + @Override + public Value execute(Value... args) { + Arguments.check(1, args.length); + if (args[0].type() != Types.FUNCTION) { + throw new TypeException(args[0].toString() + " is not a function"); + } + + final BlockingQueue queue = new LinkedBlockingQueue<>(2); + final Function synchronizer = (sArgs) -> { + try { + queue.put(sArgs[0]); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + } + return NumberValue.ZERO; + }; + final Function callback = ((FunctionValue) args[0]).getValue(); + callback.execute(new FunctionValue(synchronizer)); + + try { + return queue.take(); + } catch (InterruptedException ex) { + throw new RuntimeException(ex); + } + } + +} \ No newline at end of file diff --git a/src/com/annimon/ownlang/lib/modules/std.java b/src/com/annimon/ownlang/lib/modules/std.java index d304764..1b9e4aa 100644 --- a/src/com/annimon/ownlang/lib/modules/std.java +++ b/src/com/annimon/ownlang/lib/modules/std.java @@ -18,6 +18,7 @@ public final class std implements Module { Functions.set("time", new std_time()); Functions.set("sleep", new std_sleep()); Functions.set("thread", new std_thread()); + Functions.set("sync", new std_sync()); // String Functions.set("sprintf", new std_sprintf());