3

I'd like to kill a thread from another thread and I'd like to do when it is running, so it won't be anything like change the loop variable to something. What would be the most appropriate way to do it?

To be more clear, I am using cURL and after some point i don't want curl to perform downloading. curl API does not provide anything like that. So I have to cancel the thread.

Sarp Kaya
  • 3,686
  • 21
  • 64
  • 103
  • I suppose that this thread is running a loop.So you just have to set some shared variable (example: bool exitLoop= false; ) to true, and the thread reads the variable and exits if it's true (example: while(!exitLoop) {...} ). – Ramy Al Zuhouri Dec 19 '12 at 03:25
  • As I said above "so it won't be anything like change the loop variable to something." I update my question – Sarp Kaya Dec 19 '12 at 03:28

1 Answers1

3

Killing a thread is rarely a good idea because it can very easily lead to memory/resource leaks. A killed thread only cleans up it's stack and the memory used by the thread itself, nothing allocated via new/malloc etc.

However, if you really want to kill the thread, with pthreads the correct way to do it is to call pthread_cancel.

Also: look here:

Cancelling a thread using pthread_cancel : good practice or bad

Community
  • 1
  • 1
Nils Pipenbrinck
  • 83,631
  • 31
  • 151
  • 221
  • yeah but pthread_cancel does not work from another thread as it has not been declared within that thread... Besides in this rare situation I am cleaning up everything after cancellation. So there won't be any problem about that... – Sarp Kaya Dec 19 '12 at 03:16
  • No, you aren't necessarily cleaning everything up -- cURL may have internally allocated resources while performing the request, which it would free if it had been able to finish. If you kill it, those resources will be leaked. –  Dec 19 '12 at 03:52
  • well I actually declared threads globally. So now I can do that. Thanks! Another thing is after the cancellation the program already terminates itself. So no need to worry about anything! – Sarp Kaya Dec 19 '12 at 04:02
  • To do thread specific clean-up on cancellation one may use `pthread_cleanup_push`/`pthread_cleanup_pop`. – alk Dec 19 '12 at 06:28