Reputation: 798
I use NSThread to create a new thread, then it is executing the thread_funtion, I want to cancel the thread, I use [thread cancel], but the thread will go on.
NSThread *thread=[[NSThread alloc] initWithTarget:self selector:@selector(thread_funtion) object:nil];
[thread start];
-(void)thread_funtion
{
//my code
}
I know in the thread_funtion use flag to control its execute,it can be useful,but it is too complex.
-(void)thread_funtion
{
if(flag)
{
//some code
}
if(flag)
{
//some code
}
}
So question 1: How to cancel the thread immediately?
Then I use another method to create a new thread:
pthread_t id;
int ret;
ret=pthread_create(&id,NULL,thread_function,NULL);
if(ret!=0){
printf ("Create pthread error!\n");
exit (1);
}
Then I use pthread_cancel(id), the thread will stop immediately. But in the thread_function:
void* thread_function(void *arg)
{
//This is not a function of the class, So I can't use self.somobject !
}
So the question is ,int the c code,how to use the object of the class?
Upvotes: 0
Views: 277
Reputation: 881103
NSThread
cancellation simply sets a flag in the thread which it can discover by calling isCancelled
. It does not stop the thread if the thread is intent on continuing.
And this is actually a good thing. From my long experience in multi-threading, I'm of the opinion that theads should be in total control of themselves, including their own lifetimes.
Killing threads when they have locks on resources or while they're halfway through updating critical structures is not a good idea.
It would be a good idea to re-architect your thread functions so that they periodically call isCancelled
and act upon that. If you do it right, you can guarantee a maximum latency for response to cancellation by checking at certain points, checking within loops, ensuring any blocking calls have timeouts or ways to unblock them, and so on.
Upvotes: 3