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
attribute 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()
// Check cancellation request
if (Thread.currentThread.hasPendingCancellation) {
println("cancelled")
return
}
println("hello")
}
fut.cancel() // Send cancellation request
syncCounter.dec()
fut.get() // Join thread
}
The output is as follows.
cancelled