views:

1698

answers:

1

Hi there,

I have a call to a third-party C++ library which I have put into its own thread (currently using NSThread). I would like to give the user the ability to stop the execution of that thread. (I am well aware of all the problems this might cause, but I still wish to do so.)

According to Apple's Thread Programming Guide, there are possibilities in Cocoa to do so. Is this true for the iPhone, too, or do I have to rely on Posix threads to accomplish my goal?

Cheers

MrMage

+6  A: 

The correct way to stop your thread executing is to ask it nicely to stop executing. Then, in your thread, you listen for such requests and obey them at an appropriate time.

As the very page you linked to says:

Although Cocoa, POSIX, and Multiprocessing Services offer routines for killing threads directly, the use of such routines is strongly discouraged. Killing a thread prevents that thread from cleaning up after itself. Memory allocated by the thread could potentially be leaked and any other resources currently in use by the thread might not be cleaned up properly, creating potential problems later.

If you anticipate the need to terminate a thread in the middle of an operation, you should design your threads from the outset to respond to a cancel or exit message. For long-running operations, this might mean stopping work periodically and checking to see if such a message arrived. If a message does come in asking the thread to exit, the thread would then have the opportunity to perform any needed cleanup and exit gracefully; otherwise, it could simply go back to work and process the next chunk of data.

Peter Hosey