限制可以在示波器中运行的协程最大数量 [英] Limiting the maximum number of coroutines that can run in a scope

查看:75
本文介绍了限制可以在示波器中运行的协程最大数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将当前的应用程序从Java转换为Kotlin,然后遇到了这个问题。

I am translating our current application from Java to Kotlin and I came upon this problem.

该Java实现用于使用线程从服务器传输数据。

The java implementation used to use threads to transfer data from the server.

这将创建大约100个不同的线程来请求数据,但是根据我的观察,一次最多运行4个线程,其他线程将等待一个线程

It would create about 100 different threads that would request data, but from what I have seen no more than 4 would run at a time, the others would wait for a thread to finish before starting.

将其翻译为Kotlin时,我使用了协程(Coroutines)

When translating it to Kotlin I used Coroutines

这会造成问题,因为显然是服务器无法处理实际发送的100个请求。

This creates a problem because apparently the server can't handle 100 requests actually being sent.

所有协程都在同一范围内启动,所以就像这样:

All coroutines are launched in the same scope , so it's something like this:

//this is a custom scope that launches on Dispatchers.IO + a job that I can use to cancel everything
transferScope.launch {
     //loadData is a suspending function that returns true/false 
     val futures = mDownloadJobs.map{ async { it.loadData() } }
     val responses = futures.awaitAll()
     //check that everything in responses is true etc....
}

是否有一种方法可以使特定的transferScope一次只允许多达5个协程,然后当一个完成时让另一个运行? (我不在乎顺序)

Is there a way to make the specific transferScope to allow only up to 5 coroutines at a time and then when one finishes let a different one run? (I do not care about the order)

如果无法通过示波器完成操作,是否可以通过其他方式实现?

If it can't be done through the scope, is there a different way this can be achieved?

推荐答案

要求每个协程获得科特林 Semaphore 许可,共计5项

Require each coroutine to acquire a Kotlin Semaphore permit from a total of 5 permits before making a request.

类似这样的东西:

    import kotlinx.coroutines.sync.Semaphore

    val requestSemaphore = Semaphore(5)

    val futures = mDownloadJobs.map {
        async {
            // Will limit number of concurrent requests to 5
            requestSemaphore.withPermit {
                it.loadData()
            }
        }
    }

    val responses = futures.awaitAll()

这篇关于限制可以在示波器中运行的协程最大数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆