Terminating a Thread

You can use the cancel() method of Future<T> to send a termination request to the corresponding thread. This method does not stop the thread's execution immediately. You need to use the hasPendingCancellation property of Thread to check whether a thread has a termination request.

Generally, if there is a termination request, you can implement appropriate logic to terminate the thread. It is up to you to decide how to terminate the thread. If the termination request is ignored, the thread will continue executing until it finishes normally.

The sample code is as follows:

import std.sync.SyncCounter

main(): Unit {
    let syncCounter = SyncCounter(1)
    let fut = spawn {
        syncCounter.waitUntilZero()  // block until the syncCounter becomes zero
        if (Thread.currentThread.hasPendingCancellation) {  // Check cancellation request
            println("cancelled")
            return
        }
        println("hello")
    }
    fut.cancel()    // Send cancellation request
    syncCounter.dec()
    fut.get() // Join thread
}

The output is as follows.

cancelled