标签: coroutine

简化字符串修改功能的嵌套异步操作

我有一个异步代码,如下所示:

  • 有一个第三方函数可以对字符串执行一些操作并返回修改后的字符串,就这个问题而言,它类似于non_async_func.

  • 我有一个async def async_func_single包含non_async_func执行单个操作的函数。

  • 然后是另一个async def async_func_batch嵌套环绕的函数async_func_single来对一批数据执行该函数。

代码可以工作,但我想更多地了解为什么/如何工作,我的问题是

  • 是否有必要创建async_func_singleasync_func_batch环绕它?

  • 我可以直接输入一批数据来async_func_batch调用吗non_async_func

  • 我有一个 per_chunk 函数,可以批量输入数据,是否有任何异步操作/函数可以避免使用预批处理我想要发送的数据async_func_batch

import nest_asyncio
nest_asyncio.apply()

import asyncio
from itertools import zip_longest

from loremipsum import get_sentences

def per_chunk(iterable, n=1, fillvalue=None):
  args = [iter(iterable)] * n
  return zip_longest(*args, fillvalue=fillvalue)

def non_async_func(text):
  return text[::-1]

async def async_func_single(text):
  # Perform some string operation.
  return non_async_func(text)

async def async_func_batch(batch):
  tasks = [async_func_single(text) for …
Run Code Online (Sandbox Code Playgroud)

python string parallel-processing coroutine python-asyncio

2
推荐指数
1
解决办法
434
查看次数

挂起函数会挂起协程吗?

其实我很困惑。例如,我知道 suspendCoroutine 函数是一个挂起协程的挂起函数。但是所有的挂起函数都会挂起协程吗?此外,我知道当协程挂起时,它会从相应的线程中删除一段时间,其他协程或任务可以恢复并在该线程上运行。

我想得出的结论是,如果所有的挂起函数都不挂起协程,那么协程中的 put 挂起函数和协程中的非挂起函数有什么区别?

android suspend coroutine kotlin kotlin-coroutines

2
推荐指数
1
解决办法
496
查看次数

协程的每个执行路径上是否有必要有一个返回void的co_return语句

我想知道下面的代码是否是有效的 C++ 代码,或者如果不使用co_return会导致未定义的行为。

IAsyncAction MyClass::MyCoroutine()
{
  co_await someOtherClassInstance.SomeCoroutine();
}
Run Code Online (Sandbox Code Playgroud)

即是否需要将代码调整如下?

IAsyncAction MyClass::MyCoroutine()
{
  co_await someOtherClassInstance.SomeCoroutine();
  co_return;
}
Run Code Online (Sandbox Code Playgroud)

如果行为不是未定义的,那么最佳实践是什么(总是添加co_return或不添加)以及这样做的理由是什么?

c++ coroutine c++-winrt c++-coroutine

2
推荐指数
1
解决办法
530
查看次数

Kotlin Flow 仅每秒收集一次

我有一个下载文件的流程。该流程发出下载进度。我想在手机通知中心显示进度,但每秒只更新一次值,以防止设备滞后。

我的流程:

return callbackFlow {
  someJavaCallback { progress ->
    trySend(progress)
  }

  close()
}
Run Code Online (Sandbox Code Playgroud)

我的 CoroutineWorker,显示通知并下载文件:

myFlow.collect { // update notification }
Result.Success()
Run Code Online (Sandbox Code Playgroud)

我的问题是,如何“限制”收集,例如收集 1%,但 1 秒后它收集 5% 并忽略这两点之间的所有值

coroutine kotlin kotlin-flow

2
推荐指数
1
解决办法
2557
查看次数

了解 CoroutineScope(Job() + Dispatchers.Main) 语法

我知道什么是作业(协程的句柄),什么是调度程序(它运行的线程池)以及什么是 CoroutineScope(嗯,范围或者我们也可以说是一种组),但我不明白这个语法:

val scope = CoroutineScope(Job() + Dispatchers.Main)
Run Code Online (Sandbox Code Playgroud)

为何有人进来Job()?无论如何,我传递给的是什么CoroutineScope,它是 lambda 吗?据我所知,每当有人做这样的事情时,都会创建一份新工作:

val job = scope.launch { ... }
Run Code Online (Sandbox Code Playgroud)

那么为什么要向 CoroutineScope 中传递单个实例呢?JobCoroutineScope(Job() + Dispatchers.Main)

android coroutine kotlin kotlin-coroutines

2
推荐指数
1
解决办法
289
查看次数

如何为iPhone(ARM)构建Boost 1.56.0 boost :: context

我正在尝试为iOS开发构建增强功能,并且在github上找到了一个自动构建脚本。大多数库都运行良好,我得到了提升。我已经测试过asio库,它可以工作。

但是boost ::协程构建失败,实际上boost :: context构建因该错误而失败。

darwin.compile.c ++ iphone-build / boost / bin.v2 / libs / context / build / darwin-8.1〜iphone / release / architecture-arm / link-static / macosx-version-iphone-8.1 / target-os-iphone /threading-multi/unsupported.o libs / context / src / unsupported.cpp:7:2:错误:“不支持平台” #error“不支持平台” ^ 1错误生成。

“ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++”“ -arch”“ armv7”“ -arch”“ armv7s”“ -arch”“ arm64”“ -fvisibility = hidden “” -fvisibility-inlines-hidden“” -DBOOST_AC_USE_PTHREADS“” -DBOOST_SP_USE_PTHREADS“” -std = c ++ 11“” -stdlib = libc ++“ -ftemplate-depth-128 -O3 -finline-functions -Wno-inline -Wall -gdwarf-2 -fexceptions -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.1.sdk -pthread -arch arm -DBOOST_ALL_NO_LIB …

macos boost arm coroutine ios

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

Unity3D Coroutine编译器错误

我是一个完整的团结初学者,我想用协程播放动画,但得到以下错误:

1.error CS1502:UnityEngine.MonoBehaviour.StartCoroutine(System.Collections.IEnumerator)' has some invalid arguments 2.error CS1503: Argument#1' 的最佳重载方法匹配无法转换System.Collections.IEnumerable' expression to typeSystem.Collections.IEnumerator'


代码:

     using UnityEngine;
using System.Collections;

public class Trap : MonoBehaviour {

    //public float delayTime;


    // Use this for initialization
    void Start () {
        StartCoroutine (Go ());
    }

    // Update is called once per frame
    void Update () {

    }

    IEnumerable Go(){
        while (true) {
            animation.Play();
            yield return new WaitForSeconds(3f);
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

c# coroutine unity-game-engine

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

Python asyncio:当一个协程完成时停止循环

我在这个python asyncio主题中很新.我有一个简单的问题:我有一个包含两个协同程序的任务可以同时运行.第一个协程(my_coroutine)只会连续打印一些内容,直到达到second_to_sleep.第二个协程(seq_coroutine)将依次调用其他4个协同程序.我的目标是在seq_coroutine完全结束时停止循环.确切地说,我希望my_coroutine在seq_coroutine完成之前保持活着状态.有人可以帮助我吗?

我的代码是这样的:

import asyncio

async def my_coroutine(task,  seconds_to_sleep = 3):
    print("{task_name} started\n".format(task_name=task))
    for i in range(1, seconds_to_sleep):
        await asyncio.sleep(1)
        print("\n{task_name}: second {seconds}\n".format(task_name=task, seconds=i))

async def coroutine1():
    print("coroutine 1 started")
    await asyncio.sleep(1)
    print("coroutine 1 finished\n")


async def coroutine2():
    print("coroutine 2 started")
    await asyncio.sleep(1)
    print("coroutine 2 finished\n")


async def coroutine3():
    print("coroutine 3 started")
    await asyncio.sleep(1)
    print("coroutine 3 finished\n")


async def coroutine4():
    print("coroutine 4 started")
    await asyncio.sleep(1)
    print("coroutine 4 finished\n")


async def seq_coroutine():
    await coroutine1()
    await coroutine2()
    await coroutine3()
    await coroutine4()

def …
Run Code Online (Sandbox Code Playgroud)

python coroutine python-asyncio

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

是否正在等待阻塞Android上的UI线程?

我一直在绕着协程包头,我在想以下代码。我在onCreate()上执行以下操作。

asyncJob = GlobalScope.launch(Dispatchers.Main) {
    val name = async(Dispatchers.Default) { queryDevices() }.await()
    mDeviceName.text = deviceName
}
Run Code Online (Sandbox Code Playgroud)

将执行顺序打印出来似乎是在UI线程上的“名称”之前,以及在设置名称后,它也在UI线程上。该queryDevicesMethod()是在后台线程预期。

但是我想知道在UI线程上调用await()时实际上在做什么吗?它会阻塞UI线程直到等待返回吗?

multithreading android coroutine kotlin kotlinx.coroutines

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

启动协程统一给出空引用异常

我正在尝试从我的GameController.cs脚本访问协程,协程位于我的DatabaseManager.cs脚本中。我正在尝试像这样访问协程:

 DatabaseManager d1 = new DatabaseManager();
 d1.uploadData();
Run Code Online (Sandbox Code Playgroud)

这给了我一个空引用异常。我知道一切都在我尝试访问的协程中正常运行,因为这些脚本与我创建的另一个项目完全相同,唯一的区别是在另一个项目中我通过动画事件调用了协程,但效果很好,但是试图通过该项目中的代码调用它给了我这个问题。

数据库管理器脚本已附加到Player游戏对象

DatabaseManager脚本

using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
using UnityEngine.UI;
using CompanionLibrary; //include my library to utilise its functions
//use neccessary libraries.




    //This class handles sending game data to the database.
    public class DatabaseManager : MonoBehaviour
    {


        //declare variables to hold data values.
        static string username;
        string password;
        int score =0;
        int kills=0;  //initialise variables to 0 
        int bulletsFired=0;
        int bulletsHit=0;
        int bulletsMissed=0;
        int timePlayed = 0;
        int …
Run Code Online (Sandbox Code Playgroud)

c# coroutine unity-game-engine

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