我正在将当前的应用程序从 Java 翻译为 Kotlin,并且遇到了这个问题。
java实现过去使用线程从服务器传输数据。
它将创建大约 100 个不同的线程来请求数据,但据我所知,一次运行的线程不会超过 4 个,其他线程会等待线程完成后再开始。
将其翻译为 Kotlin 时我使用了 Coroutines
这会产生一个问题,因为显然服务器无法处理实际发送的 100 个请求。
所有协程都在同一范围内启动,所以它是这样的:
//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个协程,然后当一个协程完成时让另一个协程运行? (我不关心顺序)
如果无法通过范围来完成,是否有其他方法可以实现?
要求每个协程获取一个 KotlinSemaphore在提出请求之前,先从总共 5 个许可证中获得许可证。
像这样的东西:
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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)