Thread.sleep() in a native Kotlin project

Viewed 3541

I'm trying to create a simple native Kotlin project. I want my project to wait for X millisec during a process:

import kotlin.concurrent

fun main() {
    Thread.sleep(500);
    println("Hello world")
}

Command to compile:

kotlinc main.kt -o program.exe

But I get the following error:

main.kt:1:15: error: unresolved reference: concurrent
import kotlin.concurrent
              ^
main.kt:4:2: error: unresolved reference: Thread
        Thread.sleep(500);
        ^

I'm a bit confused, isn't this the proper way to delay my application?

2 Answers

First of all, Kotlin/Native has kotlin.native.concurrent library, that's the reason for the first error. But even in this one, there is no such function as Thread.sleep(). Instead, you can try to use platform.posix.sleep() function from the POSIX built-in library of K/N. I am not sure, what can be the use case for this approach, but if you really need to hold your threads, this might help.

If you need to be more precise than just seconds, you can use the the nanosleep function like this:

import platform.posix.nanosleep
import platform.posix.timespec

// ...

val time = cValue<timespec> {
    tv_sec = 2
    tv_nsec = 500000000
}

nanosleep(time, null)
  • tv_sec is the amount of seconds to sleep
  • tv_nsec is the additional amount of nanoseconds to sleep (0 to 999999999)

The example above waits 2.5 seconds.

Related