-
Notifications
You must be signed in to change notification settings - Fork 30
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Safer way of cancelling threads #1588
Comments
What about an API like this? threadFunc := func {
while (true) {
if (Thread currentThread() isCanceled()) // or just Thread isCanceled()
break
doSomeHeavyTask()
}
}
thread := Thread new(threadFunc) . start()
Time sleepSec(10)
thread cancel() The |
So this requires every thread instance to have a mutex ? I was thinking to keep it separated in the abstract task layer and even allow running short lived tasks directly via OS api, without the possibility to cancel them (and without allocating mutexes for them). I like the simplicity of the api though, maybe we could start with it. |
Does it, though? The flag will only change to The advantage is that it's really simple to implement, and really easy to use for example in the |
Using shared data without a lock just seems lazy, just like driving off the motorway without using the blinker. It works, but is it really how things should be done ? |
+1 |
Alright, we have a decision to implement my approach. The A |
Alright, after examination, it seems my approach won't work properly without either:
A third option is @sebastianbaginski 's approach: |
Another question: should |
Agreed. That would be consistent with the |
I'm not sure
cancel
should be in the Thread's interface now. I think we should implement cancelling logic in the client code and use a flag to just exit the thread function, without relying on the OS facilities (which are not always there or are unsafe). Writing non-blocking client code should be preferred over forcing thread termination.What I mean is, there is no safe way to terminate code such as
The client code should provide some cancellation points. Ideally every thread task could be a subclass of some abstract Task interface like
and clients implementing the interface should check if the task was cancelled inside the
run
implementation, so the previous "unsafe" example becomesand now the
Thread
class can have a safercancel
implementation, which does not rely on the OS:[ btw. Ideally we'd like to define the task subclasses in place, like in Java :) ]
I'm aware that this idea makes the Thread class less low-level and maybe slightly less convenient to use (but simple tasks could be automatically wrapped around the ThreadTask object, the use of cancellation points should be encouraged, not enforced).
The text was updated successfully, but these errors were encountered: