我认为目前的语言不存在这种支持.我认为我想做的事情可以通过"工作流引擎"来解决.但我对工作流程的问题通常是:
我已经研究了在C#中序列化迭代器,但这并没有让我到达我想要的位置.我目前正在考虑在Boo中组装一个DSL,但不确定我是否能够在Boo中获得类似coroutine的行为,并且能够将其序列化.
这是我想做的有限虚构的例子.主要问题是,在例程中的任何时候,您可能需要获得用户输入.输入之间的时间可能很长,因此需要将服务状态序列化为磁盘.
def RunMachine(user)
var lever = user.ChooseLever()
lever.Pull()
var device = CreateDevice(user)
machine.Add(device)
machine.Run()
def CreateDevice(user)
var color = user.ChooseColor()
var shape = user.ChooseShape()
return Device(color, shape)
Run Code Online (Sandbox Code Playgroud)
我在CPython中有一个工作"引擎".它捎带在python中的迭代器/ yield支持上.所以代码看起来像这样:
def escape(self, you):
roll = yield self.game.rollDice(you)
if roll < 5:
self.caughtAction(you)
Run Code Online (Sandbox Code Playgroud)
哪里rollDice可以打断.用一些用户动作.但是,CPython不会序列化迭代器.
由于游戏的整个状态可以定义为一系列命令,因此我将游戏状态序列化为协程开始的点,然后是剩余的命令列表.所以保存/恢复如下所示:
def dumpGameState(game):
if gameState.partialState:
return pickle.dumps({ 'partialState': game.partialState, 'partialInputs': game.partialInputs })
return pickle.dumps(game)
def loadGameState(data):
state = pickle.loads(data)
if state.__class__ is …Run Code Online (Sandbox Code Playgroud) 写一堂课,我该如何实施
foo.send(item)?
__iter__ 允许像生成器一样迭代类,如果我想让它成为一个协程怎么办?
我正在努力解决如何在Haskell中进行有状态计算的一般问题.例如,下面的简单算法可以在Python的生成器工具的帮助下表示为有状态但"懒惰"的计算,只执行到达下一个yield语句所需的步骤,然后将控制流返回给调用者,直到请求下一个元素为止:
def solveLP(vmax0, elems):
elem_true_ixs = [ [ ei for ei, b in enumerate(row) if b ] for row in elems ]
return go(vmax0, elem_true_ixs)
def go(vmax, mms):
if not mms:
yield []
else:
for ei in mms[0]:
maxcnt = vmax[ei]
if not maxcnt > 0:
continue
vmax[ei] = maxcnt-1 # modify vmax vector in-place
for es in go(vmax, mms[1:]):
# note: inefficient vector-concat operation
# but not relevant for this question
yield [ei]+es
vmax[ei] = maxcnt # …Run Code Online (Sandbox Code Playgroud) 我正在进行团结游戏并遇到一个我无法解决的问题.我通过标准的WWW对象连接到Web服务器并使用协程来执行POST请求.
代码本身可以工作,但是我需要更新变量值并在协程完成后返回该变量,这是我无法做到的.
public int POST(string username, string passw)
{
WWWForm form = new WWWForm();
form.AddField("usr", username);
form.AddField("pass", passw);
WWW www = new WWW(url, form);
StartCoroutine(WaitForRequest(www));
//problem is here !
return success_fail;
}
private IEnumerator WaitForRequest(WWW www)
{
yield return www;
if (www.error == null)
{
if(www.text.Contains("user exists"))
{
success_fail = 2;
}
else
{
success_fail=1;
}
} else {
success_fail=0;
}
}
Run Code Online (Sandbox Code Playgroud)
协程使用相关值更新'success_fail'的值.但'返回success_fail;' POST方法中的行在协同程序完成之前运行,这会导致它返回false值.
我试图使用额外的协程,但没有成功,假设我也有错误.如何在协程完成后返回'success_fail'值?
谢谢.
我很难学习Fibers\coroutines背后的想法和Crystal中的实现.
我希望这是一个正确的问题,我完全接受"不在这里"的答案:)
这是我在Ruby中处理多线程的常用方法:
threads = []
max_threads = 10
loop do
begin
threads << Thread.new do
helper_method(1,2,3,4)
end
rescue Exception => e
puts "Error Starting thread"
end
begin
threads = threads.select { |t| t.alive? ? true : (t.join; false) }
while threads.size >= max_threads
puts 'Got Maximum threads'
sleep 1
threads = threads.select { |t| t.alive? ? true : (t.join; false) }
end
rescue Exception => e
puts e
end
end
Run Code Online (Sandbox Code Playgroud)
这样我打开一个新的线程,通常是传入的连接或其他东西,将线程添加到线程数组,然后检查我没有更多的线程,然后我想要的.
使用spawn\channels\fiber等在Crystal中实现类似功能的好方法是什么?
在kotlinx.coroutines库中,所有协同构建器(如launch,async等)都接受CoroutineContext参数,但也有parent一个类型为的附加参数Job.CoroutineContext和之间有什么区别Job?
我正在尝试使用kotlin协同程序通过此处描述的方法访问room数据库,添加插件和依赖项,并在gradle中启用kotlin协同程序.
在gradle文件中:
kotlin {
experimental {
coroutines 'enable'
}
}
dependencies { implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:0.21" ...}
Run Code Online (Sandbox Code Playgroud)
所以我suspend为dao类中的所有方法添加了关键字,如下所示:
道类
@Query("select * from myevent")
suspend fun all(): List<MyEvent>
@Delete
suspend fun deleteEvent(event: MyEvent)
...
Run Code Online (Sandbox Code Playgroud)
并构建,然后得到这些错误
错误
e: C:\Users\projectpath\app\build\tmp\kapt3\stubs\debug\com\robyn\myapp\data\source\local\EventsDao.java:39: error: Deletion methods must either return void or return int (the number of deleted rows).
public abstract java.lang.Object deleteEventById(@org.jetbrains.annotations.NotNull()
^
e: C:\Users\projectpath\app\build\tmp\kapt3\stubs\debug\com\robyn\myapp\data\source\local\EventsDao.java:41: error: Query method parameters should either be a type that can be converted into a database column …
我正在尝试学习协同程序,因此我启动IntelliJ并创建一个临时文件.但是当我输入我的协同程序时,我得到编译器投诉,例如runBlocking未解决的引用.所以这不是一个Android项目或任何这样的事情.只是基本Kotlin项目中的临时文件.
如何引入协同程序,以便我不再收到错误?
我正在尝试从Java 7调用Kotlin函数.我正在使用协同程序,这个被调用的函数正在挂起,例如:
suspend fun suspendingFunction(): Boolean {
return async { longRunningFunction() }.await()
}
suspend fun longRunningFunction() : Boolean {
delay(400)
return true
}
Run Code Online (Sandbox Code Playgroud)
我在版本0.25.3中使用协同程序,我可以通过将Continuation<U>实例作为参数传递给挂起函数来模拟简单的Java回调样式,例如
CoroutinesKt.suspendingFunction(new Continuation<Boolean>() {
@Override
public CoroutineContext getContext() {
return EmptyCoroutineContext.INSTANCE;
}
@Override
public void resume(Boolean value) {
doSomethingWithResult(value);
}
@Override
public void resumeWithException(@NotNull Throwable throwable) {
handleException(throwable);
}
});
Run Code Online (Sandbox Code Playgroud)
但是,在更新到完全稳定的1.0.1版本后,我认为它已不再可能.假设暂停函数的更新版本如下所示:
suspend fun suspendingFunction(): Boolean {
return GlobalScope.async { longRunningFunction() }.await()
}
Run Code Online (Sandbox Code Playgroud)
Continuation<U>现在使用Result类,它似乎无法从Java中使用(这是有意义的,因为它是内联类).我试图使用Continuation协同程序的一些子类,但它们都是内部或私有的.
我知道通常建议将协程转换为CompletableFuture,但我在Android上,这意味着只有Java 7.Future另一方面,简单是太愚蠢,因为我不想定期检查函数是否完成 …
已开始尝试在JUnit单元测试中使用kotlinx-coroutines-test(https://github.com/Kotlin/kotlinx.coroutines/blob/master/core/kotlinx-coroutines-test/README.md)但在我调用时遇到以下错误Dispatchers.setMain()
java.lang.IllegalArgumentException: TestMainDispatcher is not set as main dispatcher, have Main[missing, cause=java.lang.AbstractMethodError: kotlinx.coroutines.test.internal.TestMainDispatcherFactory.createDispatcher()Lkotlinx/coroutines/MainCoroutineDispatcher;] instead.
at kotlinx.coroutines.test.TestDispatchers.setMain(TestDispatchers.kt:22)
Run Code Online (Sandbox Code Playgroud)
我试过打电话Dispatchers.setMain(Dispatchers.Unconfined)也传入了val mainThreadSurrogate = newSingleThreadContext("UI thread").看起来似乎问题不是传递价值,而是mainDispatcher在接下来的测试中绊倒
public fun Dispatchers.setMain(dispatcher: CoroutineDispatcher) {
require(dispatcher !is TestMainDispatcher) { "Dispatchers.setMain(Dispatchers.Main) is prohibited, probably Dispatchers.resetMain() should be used instead" }
val mainDispatcher = Dispatchers.Main
require(mainDispatcher is TestMainDispatcher) { "TestMainDispatcher is not set as main dispatcher, have $mainDispatcher instead." }
mainDispatcher.setDispatcher(dispatcher)
}
Run Code Online (Sandbox Code Playgroud)