So I have a very small array of `List<Particle&...
# kotlin-native
d
So I have a very small array of `List<Particle>`s. These particles have mutable state so I can't freeze them. I'd like to process each list in a different thread/worker. How would I be able to do this? How could I detach/transfer them? All the examples I've seen have the worker create the data themselves. As supposed to working on existing data.
o
you could use smth like
Copy code
import kotlin.native.concurrent.*
import kotlin.random.Random
import platform.posix.usleep
import kotlinx.cinterop.convert

data class Job(val index: Int, var input: Int, var counter: Int)

fun initJobs(count: Int) = Array<Job?>(count) { i -> Job(i, i * 2, i)}

fun main() {
    val COUNT = 100
    val workers = Array(COUNT, { _ -> Worker.start() })
    val jobs = initJobs(COUNT)
    val futures = Array(workers.size, { workerIndex ->
        workers[workerIndex].execute(TransferMode.SAFE, {
            val job = jobs[workerIndex]
            jobs[workerIndex] = null
            job!!
        }) { job ->
            job.counter += job.input
            job
        }
    })
    val futureSet = futures.toSet()
    var consumed = 0
    while (consumed < futureSet.size) {
        val ready = futureSet.waitForMultipleFutures(10000)
        ready.forEach {
            it.consume { job ->
                jobs[job.index] = job
            }
            consumed++
        }
    }
    workers.forEach {
        it.requestTermination().result
    }
}
, note that due to bug, fixed in https://github.com/JetBrains/kotlin-native/pull/2135
TransferMode.UNSAFE
shall be used for that code to work, if used with current K/N version
d
Perfect!