标签: coroutine

C#中的纤维:它们比迭代器更快,并且让人们使用它们?

所以我正在和一位同事聊聊有关光纤的问题,在2003年发表这篇论文,描述了使用Fiber API在C#中实现协同程序.

本文的实现Yield是针对.NET 1.1的,因此它早yield return于.NET 2.0中出现的语法.

乍一看,它确实看起来这里的实现可能更快,并且可以很好地扩展到多个CPU.

有人用过吗?

c# yield coroutine fiber

8
推荐指数
2
解决办法
4120
查看次数

Python 生成器发送:发送后不产生新值

这是一个奇怪的问题,所以我将解释:

我有一个像这样的生成器,它充当 IRC 服务器的生成器前端:

def irc_iter(): # not the real code, simplified
    msgs = get_msgs()
    for msg in msgs:
        if is_ping(msg):
            pong()
        else:
            to_send = yield msg
            for s in to_send:
                send(s)
Run Code Online (Sandbox Code Playgroud)

从理论上讲,这应该允许我做一些很酷的事情,例如:

server = connect()
for line in server:
       if should_respond(line):
           server.send('WOW SUCH MESSAGE')
Run Code Online (Sandbox Code Playgroud)

但是,有一个问题:也会generator.send 产生下一个值。这意味着这server.send也给了我下一条消息......我更愿意像所有其他消息一样处理它,产生为line.

我知道我可以用一种丑陋的方式来解决这个问题,在接收到发送后只产生一个垃圾值,但我试图保持我的代码优雅,但恰恰相反。有没有办法告诉生成器我还不需要新值?

谢谢。

python yield generator yield-keyword coroutine

8
推荐指数
1
解决办法
1126
查看次数

有没有办法重用Job实例?

我正在探索在Android UI线程的上下文中使用协同例程.我contextJob按照Coroutines Guide UI中的描述实现了.后台工作从GUI开始,我想在每次点击时重新启动它(停止当前运行的并重新启动它).

但是一旦被取消的工作就无法重复使用,所以甚至创造了一份儿童工作:

 val job = Job(contextJob)
Run Code Online (Sandbox Code Playgroud)

并取消它并没有帮助,因为它必须被重新分配.

有没有办法重用Job实例?

android coroutine async-await kotlin kotlin-coroutines

8
推荐指数
1
解决办法
1308
查看次数

在协程中使用全局状态变量?

我正在使用 discord.py 库构建一个 discord bot - 因此所有用户交互都必须在协程中进行,使用 async 定义并使用 await 调用。

我的一个函数将需要一个保存的状态变量 - 计算中使用的时间偏移量,偶尔需要由用户手动更新。

我不能在主线程中使用普通的全局变量——协程看不到它们。在多个协程之间保留状态变量的明智设计模式是什么?

python global-variables coroutine

8
推荐指数
1
解决办法
546
查看次数

如何处理协同程序函数的多个结果?

我有一些生成器做一些搜索的东西,我使用另一个生成器包装它们:

def searching_stuff_1():
    # searching
    yield 1
    # and searching
    yield 2
    yield 3

def searching_stuff_2():
    yield 4
    yield 5


def gen():
    yield from searching_stuff_1()
    yield from searching_stuff_2()

for result in gen():
    print(result)
Run Code Online (Sandbox Code Playgroud)

所以现在我想知道如何将其重写为异步版本,这可以在searching_stuff_1和searching_stuff_2中产生多个值.

我在努力:

import asyncio

async def searching_stuff_1():
    f = asyncio.Future()
    result = []
    await asyncio.sleep(1)
    #searching
    result.append(1)
    #searching
    result.append(2)
    result.append(3)
    f.set_result(result)
    return f

async def searching_stuff_2():
    f = asyncio.Future()
    result = []
    await asyncio.sleep(1)
    result.append(4)
    result.append(5)
    f.set_result(result)
    return f

async def producer():
    coros = [searching_stuff_1(), searching_stuff_2()]
    for …
Run Code Online (Sandbox Code Playgroud)

python asynchronous generator coroutine python-3.x

8
推荐指数
1
解决办法
665
查看次数

Kotlin:coroutineScope 比 GlobalScope 慢

我正在学习协程,我遇到了以下令人惊讶的(对我而言)行为。我想要一张平行地图。我考虑了4个解决方案:

  1. 只是map,没有并行性
  2. pmap这里
  3. 修改第 2 项:我删除coroutineScope并使用GlobalScope.
  4. Java 的parallelStream.

编码:

import kotlinx.coroutines.*
import kotlin.streams.toList
import kotlin.system.measureNanoTime

inline fun printTime(msg: String, f: () -> Unit) =
    println("${msg.padEnd(15)} time: ${measureNanoTime(f) / 1e9}")

suspend fun <T, U> List<T>.pmap(f: (T) -> U) = coroutineScope {
    map { async { f(it) } }.map { it.await() }
}

suspend fun <T, U> List<T>.pmapGlob(f: (T) -> U) =
    map { GlobalScope.async { f(it) } }.map { it.await() …
Run Code Online (Sandbox Code Playgroud)

parallel-processing performance coroutine kotlin kotlin-coroutines

8
推荐指数
1
解决办法
2273
查看次数

重复构建失败“要使用协程功能,您必须添加`ktx`.......”

我是 Kotlin 和 Android Studio 的新手,我目前的问题是......
我正在尝试让 Codelabs“android-room-with-a-view-kotlin”工作,同时修复各种构建错误,我认为我的 build.gradle 变得非常混乱!我通过添加依赖项更正了Word.kt 上的最后一次构建失败

kapt 'androidx.room:room-ktx:2.2.1'
Run Code Online (Sandbox Code Playgroud)

下一个构建在WordDao.kt更进一步,但由于相同类型的错误而失败。

WordDao.java:21: error: To use Coroutine features, you must add `ktx` artifact from Room as a dependency. androidx.room:room-ktx:<version>
Run Code Online (Sandbox Code Playgroud)

我无法继续,因为我不知道要在 build.gradle 中更改什么,因为我已经添加了该依赖项?

正如我已经说过我的文件现在很迷茫,我将不胜感激任何以使其更明智的援助。谢谢, DaveInUk

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: "kotlin-kapt"

android {
    compileSdkVersion 28
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.prepopplus"
        //was minSdkVersion 15  Note Old phone is API16
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1 …
Run Code Online (Sandbox Code Playgroud)

android coroutine kotlin android-room

8
推荐指数
2
解决办法
5572
查看次数

如何在kotlin中使用Coroutine每秒调用一个函数

我刚刚创建了一个应用程序,其中我的函数 getdata() 每秒调用一次以从服务器获取新数据,而 updateui() 函数将更新 UI 中的视图我没有在我的应用程序中使用任何异步任务或协程我想这样做请告诉我我怎么能做到这一点。

这是我的代码...

private fun getdata(){
        try {
            val api = RetroClient.getApiService()
            call = api.myJSON
            call!!.enqueue(object : Callback<ProductResponse> {
                override fun onResponse(
                    call: Call<ProductResponse>,
                    response: Response<ProductResponse>
                ) {
                    if (response.isSuccessful) {
                        productList = response.body()!!.data
                        for (list in productList) {
                            if (list.BB.equals("AAA")) {
                                aProductList.add(list)
                            }
                        }
                        if (recyclerView.adapter != null) {
                            eAdapter!!.updatedata(aProductList)
                        }
                        updateui()
                    }
                }

                override fun onFailure(call: Call<ProductResponse>, t: Throwable) {
                    println("error")
                }
            })
        } catch (ex: Exception) {
        } catch (ex: OutOfMemoryError) { …
Run Code Online (Sandbox Code Playgroud)

android coroutine kotlin

8
推荐指数
4
解决办法
8963
查看次数

在 Unity 中,我什么时候应该使用协程而不是在 Update() 中减去 Time.deltaTime?

下面是我想强调的差异的一个简单示例。

使用协程:

public float repeatRate = 5f;
void Start()
{
    StartCoroutine("RepeatSomething");
}
IEnumerator RepeatSomething()
{
    while (true)
    {
        yield return new WaitForSeconds(repeatRate);
        // Do something
    }
}
Run Code Online (Sandbox Code Playgroud)

使用Update()Time.deltaTime

public float repeatRate = 5f;
private float timer = 0;
void Update()
{
    if (timer < 0)
    {
        // Do something
        timer = repeatRate;
    }
    timer -= Time.deltaTime;
}
Run Code Online (Sandbox Code Playgroud)

我什么时候应该使用一个而不是另一个,每个的优点/缺点是什么?

c# time ienumerator coroutine unity-game-engine

8
推荐指数
2
解决办法
2411
查看次数

协程和带有静态变量的函数有什么区别?

我一直在学习 C++20 中的新功能,并试图了解共同讨论的共同例程的“生成器”用例。我试图在这里创建一个小例子,但如果有错误,我深表歉意:

generator<int> Generate() {
    int i = 0;
    while(1) {
        co_yield i++;
    }
}

int main()
{
    auto gen { Generate() };
    for (int x = 0; x < 10; ++x) {
        gen.next();
        std::cout << gen.getValue() << std::endl;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是我看不出这与具有静态变量的函数有何不同,例如:

auto gen() {
    static int i = 0;
    return i++;
}

int main()
{
    for (int x = 0; x < 10; ++x)
        std::cout << gen() << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我想我可能会看到异步 I/O 是一个用例,尤其是使用co_await …

c++ coroutine c++20

8
推荐指数
1
解决办法
376
查看次数