terminating a secondary thread from the main thread (cocoa)

前端 未结 2 2173
北恋
北恋 2021-02-09 20:55

I\'m working on a small app written in objective-c with the help of the cocoa framework and I am having a multithreading issue. I would really appreciate it if somebody could he

2条回答
  •  爱一瞬间的悲伤
    2021-02-09 21:05

    I think the easiest way is to use NSThread's -(void)cancel method. You'll need a reference to the thread you've created, as well. Your example code would look something like this, if you can do the worker thread as a loop:

    - (IBAction)startWorking:(id)sender {
         myThread = [[NSThread alloc] initWithTarget:self selector:@selector(threadMain:) object:nil];
         [myThread start];
    }
    
    - (void)threadMain
    {
        while(1)
        {
            // do IO here
            if([[NSThread currentThread] isCancelled])
                break;
        }
    }
    
    - (IBAction)stop:(id)sender {
       [myThread cancel];
       [myThread release];
       myThread = nil; 
    }
    

    Of course, this will only cancel the thread between loop iterations. So, if you're doing some long blocking computation, you'll have to find a way to break it up into pieces so you can check isCancelled periodically.

提交回复
热议问题