标签: coroutine

python3 生成器中的 send() 函数

根据docs, send() 函数:

\n\n
\n

“恢复执行,并将 \xe2\x80\x9csends\xe2\x80\x9d 一个值发送到生成器函数中。value 参数成为当前生成表达式的结果。send() 方法返回生成器生成的下一个值,或者如果生成器退出而没有产生另一个值,则引发 StopIteration。当调用 send() 来启动生成器时,必须使用 None 作为参数来调用它,因为没有可以接收该值的 Yield 表达式。

\n
\n\n

但我不明白,为什么“值参数成为当前yield表达式的结果”在下面的例子中没有发生:

\n\n
def gen():\n    yield 1\n    x = (yield 42)\n    print(x)\n    yield 2\n\n>>>c=gen() #create generator\n>>>next(c) #prints \'1\' and stop execution, which is caused by yield 1\n>>>c.send(100) #prints \'42\', because \'The send() method returns the next value yielded by the generator\'\n>>>next(c) #prints \'None\' and \'2\'\n
Run Code Online (Sandbox Code Playgroud)\n\n

那么为什么 x 变量保持“无”,尽管我通过 c.send(100) 向它发送了 100?看来,右侧的yield表达式分两步工作:首先,它将值返回给生成器的调用者,第二步,它返回生成器内发送函数的参数。如果在 send(42) 之前添加额外的 next(c) 我将得到预期的行为并且程序打印“100”。从文档中我不清楚为什么当我调用 send() 时这两个步骤不应同时发生。

\n

python coroutine python-3.x

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

将协程函数作为函数参数传递

我需要传递一个协程函数作为另一个函数的参数。例如:

private fun handleIt(here: Long, call: (hereId: Long) -> Unit) {
            call(here)
}
Run Code Online (Sandbox Code Playgroud)

然后从协程范围:

GlobalScope.launch {
                        handleIt(3) { viewModel.doThings(hereId) }
                    }
Run Code Online (Sandbox Code Playgroud)

viewModel 函数如下所示:

suspend fun doThings(hereId: Long) {
        withContext(coroutineContextProvider.io) {
            doSomething(hereId)
        }
    }
Run Code Online (Sandbox Code Playgroud)

但现在,我收到错误:“只能在协程体内调用暂停函数。有什么建议吗?

coroutine higher-order-functions kotlin

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

Python Discord.py `time.sleep()` 协程

import discord

import os
import random
import time
import math


client = discord.Client()

with open('admins.conf', 'r') as f:
    for line in f.readlines():
        exec(line)
with open('bans.conf', 'r') as f:
    for line in f.readlines():
        exec(line)
with open('coins.conf', 'r') as f:
    for line in f.readlines():
        exec(line)

random.seed(os.urandom(32))
searchusers = []

@client.event
async def on_ready():
    '''Notification on ready.'''
    print('Logged in! Bot running.')
    await client.change_presence(activity=discord.Game(name='/help'))

def getcoins(uid):
    '''Get the amount of coins, if nonexistent set to 0.'''
    try:
        return coins[uid][0]
    except Exception:
        coins[uid] = [0, …
Run Code Online (Sandbox Code Playgroud)

python coroutine discord.py

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

如何使用 Kotlin 协程处理 Android 传感器事件?

我想以面向流的方式处理 Android 上的传感器事件,最好使用 Kotlin 的协程。

对于传感器我知道如何实现回调SensorEventListener接口 public void onSensorChanged(SensorEvent event);

我怎样才能将数据发送到其中kotlinx.coroutines.channels.Channel

android coroutine android-sensors kotlin kotlin-coroutines

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

在协程流程中组合多个 Firestore 任务

下面的代码通过使用协程流从 firestore 获取数据,给出了我想要的结果。

 suspend fun getFeedPer() = flow<State<Any>> {
    emit(State.loading())

    val snapshot = dbRef.collection("FeedInfo/FeedPercent/DOC/")
        .whereGreaterThanOrEqualTo("bodyWeight", 0.80)
        .limit(1)
        .get().await()
    val post = snapshot.toObjects(FeedPer::class.java)
    Log.d("TAG", "getFeedPer: ${snapshot.documents[0].id}")
    Log.d("TAG", "getFeedPer: $post")
    emit(State.success(post))
}.catch {
    emit(State.failed(it.message.toString()))
}.flowOn(Dispatchers.IO)
Run Code Online (Sandbox Code Playgroud)

现在我正在尝试向我的查询添加一个过滤器。为此,我正在使用任务。

    val docRef=dbRef.collection("FeedInfo/FeedPercent/DOC/")
    val task1=docRef.whereGreaterThanOrEqualTo("bodyWeight", 0.80)
        .limit(1).get()
    val task2=docRef.whereLessThanOrEqualTo("bodyWeight", 0.80)
        .limit(1).get()
Run Code Online (Sandbox Code Playgroud)

现在如何通过协程流程来完成它。

请帮忙谢谢

coroutine kotlin google-cloud-firestore kotlin-coroutines

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

如何每X秒调用一次协程?

我正在尝试创建一个每 2 秒运行一次协程的类。如果它有效,它应该每 2 秒打印一次到控制台“Ran”。然而,当前版本只是打印控制台似乎每一帧。从逻辑上如何解决这个问题?

public class EveryXSeconds: MonoBehaviour
{

    public bool running = true;

    private void Update()
    {
        StartCoroutine(MyCoroutine());
    }

    IEnumerator MyCoroutine()
    {
        // Set the function as running
        running = true;

        // Do the job until running is set to false
        while (running)
        {
            // Do your code
            print("Ran");

            // wait for seconds
            yield return new WaitForSeconds(2f);
            running = false;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

coroutine unity-game-engine

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

如何使用参数收集 ViewModel 中的流

我在存储库中有一个函数,它根据参数从网络或远程数据源返回响应。

图书库:

suspend fun getBooks(isNetwork: Boolean) : Flow<Books>
Run Code Online (Sandbox Code Playgroud)

我想在视图模型中收集它,但每次调用 ViewModel 方法时都会创建一个新的协程。我知道我应该在暴露给 UI 层之前映射流程,但是如何将参数传递给函数呢?

图书视图模型:

fun getBooks(isNetwork: Boolean) {
        viewModelScope.launch {
            bookRepository.getBooks(isNetwork).collectLatest { books ->
             ...
            }
        }
}
Run Code Online (Sandbox Code Playgroud)

这里getBooks函数也用于进行网络调用,需要多次调用。每次调用 ViewModel 中的 getBooks 时,都会创建一个新的协程,从而创建多个观察者。

android mvvm coroutine kotlin-flow

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

协程似乎并不比 JVM 线程占用更少的资源

我做了一个基准测试(参考答案来测试线程池中coroutiens和线程之间的内存使用情况:

val COUNT = 4_000

val executor: Executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors())// 12 cores on my machine
 fun main(array: Array<String>)  = runBlocking{
     val latch = CountDownLatch(COUNT)
     val start = System.currentTimeMillis()
     repeat(COUNT) {
         launch(Dispatchers.Default) {
             testByCoroutine(latch)
         }
     }
     latch.await()
     println("total: " + (System.currentTimeMillis() - start))


     // testByThreadPool()
 }


fun testByThreadPool() {
    val latch = CountDownLatch(COUNT)
    val start = System.currentTimeMillis()
    for (i in 0..<COUNT) {
        executor.execute {
            val num: Int = request1()
            println(request2(num))
            latch.countDown()
        }
    }
    try {
        latch.await()
    } catch (e: …
Run Code Online (Sandbox Code Playgroud)

java multithreading coroutine kotlin kotlin-coroutines

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

如何在Python中使用带协同程序的装饰器?

我正在尝试制作一个程序,它产生两个互相交流的进程.我已经阅读了关于协同程序的内容,并认为这次采用它会很好,而且由于协程在使用之前需要启动,我认为让装饰器自动完成它会很好.

import multiprocessing as mp
import random
import time
import os
from datetime import datetime, timedelta
from functools import wraps

output, input = mp.Pipe()



def co_deco(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        cr = func(*args, **kwargs)
        cr.send(None)
        return cr
    return wrapper

class sender(mp.Process):
    def __init__(self, pipe):
        mp.Process.__init__(self)
        self.pipe = pipe

    def run(self):
        print('RECEIVER PID: ', os.getpid() )
        while True:
            self.pipe.send( random.randint(0,10) )
            time.sleep(1)

class receiver(mp.Process):
    def __init__(self, pipe):
        mp.Process.__init__(self)
        self.pipe = pipe

    def run(self):
        while True:
            self.coroutine.send( self.pipe.recv() )

    @co_deco
    def coroutine(self): …
Run Code Online (Sandbox Code Playgroud)

python coroutine python-decorators

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

尽管使用异步,为什么我仍然会收到NetworkOnMainThreadException?

这是我的程序,用于显示我在Android设备上制作的Web应用程序(数据产品)的结果。

package studio.nyaa.crimeprediction

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import java.net.URL
import android.util.Log
import android.widget.TextView
import com.beust.klaxon.JsonObject
import com.beust.klaxon.Parser
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.async

suspend fun obtainJson():JsonObject {
    val sourceURL = "http://yingzhou474.pythonanywhere.com/api"
    val jsonRes: String = URL(sourceURL).readText()
    val parser: Parser = Parser.default()
    val json = parser.parse(jsonRes) as JsonObject
    Log.d("oj", "oj finished")
    return json
}
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        runBlocking {
            val json = async{obtainJson()}.await()
            Log.d("postcoroutine", json.toString())
            val crime1: Double? = json.obj("data")?.double("AGGRAVATED ASSAULT")
            val crime2: Double? …
Run Code Online (Sandbox Code Playgroud)

android asynchronous coroutine kotlin kotlin-coroutines

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