Kotlinx.coroutines: Kotlin/Native runBlocking & delay cause high CPU usage

Created on 27 May 2019  路  2Comments  路  Source: Kotlin/kotlinx.coroutines

Hi all,

I just started a very simple hello world console application with Kotlin/Native for a linuxX64 target.
I want to increment a counter and print it every two seconds to the command line:

fun main() = runBlocking {
    var i = 0
    while(isActive){
        println("Hello Kotlin/Native COROUTINE #${++i}")
        delay(2000)
    }
}

When I run the binary on a the target host I encounter that CPU usage increases by 25% (one core being totally occupied). So it seems this is blocking the thread totally.

When I replace the delay(...) suspend function with a platform.posix.sleep(2) there is no noticeable CPU usage increase (0%).

here my _build.gradle.kts_:

plugins {
    kotlin("multiplatform") version "1.3.30"
}

repositories {
    mavenCentral()
}


kotlin {
    linuxX64("native") {
        binaries {
            executable()
        }
    }

    sourceSets {
        val nativeMain by getting {
            dependencies {
                implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core-native:1.2.1")
            }
        }

    }
}

tasks.withType<Wrapper> {
  gradleVersion = "5.3.1"
  distributionType = Wrapper.DistributionType.ALL
}

Is this a known issue ? or is just me being new to Kotlin/Native and coroutines... (bear with me if that's the case)

Many thanks for your support and the great efforts you put into bringing Kotlin coroutines to every platform !

Best regards,
Thomas

enhancement

Most helpful comment

It's a known issue waiting for someone to report it :)

All 2 comments

It's a known issue waiting for someone to report it :)

Good to hear that :smiley:. Looking forward to this issue being fixed.

For those who are looking for a temporary workaround for Koltin/Native & Multiplatform projects targeting POSIX compliant targets:

expected declaration in common/platform independent code

expect suspend fun delayOnPlatform(timeMillis: Long)

actual declaration in POSIX compliant module

actual suspend fun delayOnPlatform(timeMillis: Long) {
    memScoped {
        val timespec = alloc<timespec>()
        timespec.tv_sec = timeMillis / 1000
        timespec.tv_nsec = ((timeMillis % 1000L) * 1000000L).convert()
        nanosleep(timespec.ptr, null)
    }
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

elizarov picture elizarov  路  3Comments

zach-klippenstein picture zach-klippenstein  路  3Comments

iTanChi picture iTanChi  路  3Comments

IgorKey picture IgorKey  路  3Comments

petersamokhin picture petersamokhin  路  3Comments