Skip to content

Commit

Permalink
docs: add docs for pmap
Browse files Browse the repository at this point in the history
  • Loading branch information
Adriankhl committed Dec 10, 2023
1 parent 4225675 commit 042d93b
Showing 1 changed file with 20 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -153,28 +153,35 @@ class CoroutineVar<T>(init: T) {


/**
* parallel map collection by coroutine
* Concurrently transform a collection into a list by coroutine
*
* @param f a function mapping an element in the collection into a new element
* @return A list containing the transformed elements
*/
suspend fun <A, B> Collection<A>.pmap(f: suspend (A) -> B): List<B> = coroutineScope {
withContext(Dispatchers.Default) {
/*
val threads = Thread.getAllStackTraces().keys.filter {
it.name.startsWith("CommonPool") || it.name.startsWith("ForkJoinPool")
}
println("Number of thread in coroutine: " + threads.size )
*/
// A peace of code to test how many threads are being used
//val threads = Thread.getAllStackTraces().keys.filter {
// it.name.startsWith("CommonPool") || it.name.startsWith("ForkJoinPool")
//}
//println("Number of thread in coroutine: ${threads.size}")
map { async { f(it) } }.awaitAll()
}
}

/**
* Concurrently transform a map into a list by coroutine
*
* @param f a function mapping the key and the value in the map into a new element
* @return A list containing the transformed elements
*/
suspend fun <K, V, B> Map<K, V>.pmap(f: suspend (K, V) -> B): List<B> = coroutineScope {
withContext(Dispatchers.Default) {
/*
val threads = Thread.getAllStackTraces().keys.filter {
it.name.startsWith("CommonPool") || it.name.startsWith("ForkJoinPool")
}
println("Number of thread in coroutine: " + threads.size )
*/
// A peace of code to test how many threads are being used
//val threads = Thread.getAllStackTraces().keys.filter {
// it.name.startsWith("CommonPool") || it.name.startsWith("ForkJoinPool")
//}
//println("Number of thread in coroutine: ${threads.size}")
map { async { f(it.key, it.value) } }.awaitAll()
}
}

0 comments on commit 042d93b

Please sign in to comment.