Forum OpenACS Q&A: Response to Killing an Aolserver thread?

Posted by Drazen Kacar on
Pthreads have pthread_cancel function, which can be used to cancel a thread. However, when you cancel a thread all resources acquired by that thread remain acquired. That means that nothing will release the memory, so you effectively end up with the memory leak.

Even worse, if that thread has locked some mutex, the mutex will remain locked. Since only the thread which locked the mutex can unlock it, this means that the resource the mutex was guarding remains locked for the lifetime of the process. In other words, forever.

How bad that is depends on the nature of the resource, but it's definitely bad and might turn out to be a disaster.

So don't cancel threads. Pthreads have pthread_cleanup_push and pthread_cleanup_pop mechanism which is intended for cancelation cleanup work, though. But that's mainly for the library authors who want to write a decent software. Applications rarely bother with it (as there's not much point). As far as I know, AOLserver doesn't have that mechanism in place. And I don't think it should.

Again, don't just blindly cancel threads. What you want to do is cancel a certain Tcl interpreter. That's a completely different thing. The fact that it runs in a separate thread is just an implementation detail.

Now, I'm not aware of a mechanism which you could use to cancel the interpreter. The easiest and safest thing to do would be to add a piece of code in your long running job which would periodicaly check some shared variable. In case that variable is set, just exit.

In case you want to cancel a thread which takes too much resources because there's just a plain bug somewhere, I think you'll have to fix that bug. Multithreaded programs don't leave you much options there.