Creating a Thread

If you want to execute a segment of code concurrently, you only need to create a Cangjie thread. To create a Cangjie thread, you can use the keyword spawn next to a lambda expression with no parameters. The lambda expression contains the code to be executed in the new thread.

In the following sample code, both the main thread and the new thread attempt to print some text:

import std.sync.*
import std.time.*

main(): Int64 {
    spawn { =>
        println("New thread before sleeping")
        sleep(100 * Duration.millisecond) // sleep for 100ms.
        println("New thread after sleeping")
    }

    println("Main thread")

    return 0
}

Here, the new thread stops when the main thread ends, regardless of whether the new thread has completed its execution. The output of the example may vary slightly each time it runs, potentially resembling the following:

New thread before sleeping
Main thread

The sleep() function enforces the current thread to suspend for an at least specified duration (determined by the Duration type) and then resume the execution. For details, see Thread Sleep Duration.