How to exit NSThread

前端 未结 2 1750
面向向阳花
面向向阳花 2020-12-18 11:44

I am using a thread like this,

[NSThread detachNewThreadSelector:@selector(myfunction) toTarget:self withObject

the thread is running corre

相关标签:
2条回答
  • 2020-12-18 11:59

    In which thread are you running "[NSThread exit]"? [NSThread exit] runs in the current thread so you need to call this as part of the myfunction selector. If you call it in the main thread, it will just exit the main thread.

    Also, it's not a good idea to stop threads like this as it prevents the thread being exited from cleaning up resources.

    myfunction should exit based on a shared variable with the coordinating thread.

    - (void) myFunction
    {
        while([someObject stillWorkToBeDone]) 
        { 
          performBitsOfWork();
        }
    }
    

    You can share a reference between the coordinating thread and the worker thread using "withObject". In this way, the coordinating thread could change an instance variable in the shared object so that the worker thread could stop it's work based on this condition.

    To exit the worker thread the coordinating thread would just call smth like:

    [someObject setStillWorkToBeDone:false];
    
    0 讨论(0)
  • 2020-12-18 12:11

    You should call

    -[NSThread cancel]
    

    on the thread you created and check for

    -[NSThread isCancelled]
    

    in your while loop.

    0 讨论(0)
提交回复
热议问题