Skip to content

Instantly share code, notes, and snippets.

@ericwomer
Created January 25, 2023 11:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericwomer/8921f3123392a9451ac89a4957c3ebbd to your computer and use it in GitHub Desktop.
Save ericwomer/8921f3123392a9451ac89a4957c3ebbd to your computer and use it in GitHub Desktop.
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import kotlin.coroutines.coroutineContext
fun main(args: Array<String>) = runBlocking<Unit> {
asyncTest()
}
suspend fun asyncTest() {
val startTime = System.currentTimeMillis()
val count = 826
val cores = Runtime.getRuntime().availableProcessors()
val quotent: Int = count / cores
val remainder: Int = count % cores
var asyncCount = 0
var forCount = 0
val scope = CoroutineScope( Dispatchers.Default)
var dotList = mutableListOf<String>("")
var numberList = mutableListOf<Int>()
var iList = mutableListOf<Int>()
var jList = mutableListOf<Int>()
println("count is $count, number of cores is $cores, the quotent is $quotent and the reminader is $remainder")
withContext(coroutineContext) {
for(i in 1 .. (count - remainder) step (cores )) {
forCount = i + (cores - 1)
println("forCount == $forCount")
asyncCount++
async(Dispatchers.Default) {
for (j in i..forCount) {
jList.add(j)
iList.add(i)
dotList.add(".")
delay(2) // Work
}
}
numberList.add(asyncCount)
}
}
asyncCount++
forCount++
numberList.add(asyncCount)
println("forCount == $forCount")
if(remainder != 0) {
withContext(coroutineContext) {
async(Dispatchers.Default) {
for (i in forCount..(forCount + remainder)) {
dotList.add(".")
delay(2) // Work
}
}
}
}
println("iList.count() == ${iList.count()}")
iList.sort()
println("iList == $iList")
println("asyncCount == $asyncCount")
println("Number of dots == ${dotList.count()}")
println("Time elapsed: ${elapseMillis(startTime = startTime)}ms")
println("Dots: ${dotList.toString()}")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment