← Back to lessons

42 Threads

Hard

You can easily create threads in Cangjie using spawn.

Example function we will be calling.

Suppose we have a function call f(s). Here’s how we’d call that in the usual way, running it synchronously.

To invoke this function in a new thread, use spawn { => f(s) }. This new thread will execute concurrently with the calling one.

You can also start a new thread with an anonymous function call inside.

Our two function calls are running asynchronously in separate threads now. Wait for them to finish (for a more robust approach, use get() on the result of thread).

When we run this program, we see the output of the blocking call first, then the output of the two threads. The threads output may be interleaved, because goroutines are being run concurrently.

threads.cj
import std.time.*
import std.sync.*

func f(from: String) {
    for (i in 0..3) {
        println("${from}:${i}")
        sleep(Duration.millisecond * 100)
    }
}

main() {
    f("direct")

    spawn {=>
        f("Cangjie Thread")
    }

    // Remember that `=>` is omissible here
    // as there are no arguments for the lambda
    spawn {
        {mess: String => println(mess)}("going")
    }

    sleep(Duration.second)
    println("done")
}

/*
direct:0
direct:1
direct:2
Cangjie Thread:0
going
Cangjie Thread:1
Cangjie Thread:2
 */