Completion of the secondary stream from the main stream (cocoa)

I am working on a small application written in objective-c using the cocoa framework, and I have a multithreading problem. I would really appreciate it if someone could help me with some guidance on how to stop the secondary (worker) thread from the main thread?

- (IBAction)startWorking:(id)sender { [NSThread detachNewThreadSelector:@selector(threadMain:) toTarget:self withObject:nil]; } - (void)threadMain { // do a lot of boring, time consuming I/O here.. } - (IBAction)stop:(id)sender { // what now? } 

I found something on apple docs , but in this example there is no part in which the input runloop source changes the value of exitNow.

In addition, I will not use many threads in my application, so I would prefer a simple solution (at a lower cost) than a more complex one, which could easily manage many threads, but with a lot of overhead (for example, using locks, maybe (?) instead of runloops)

Thanks in advance

+6
multithreading objective-c cocoa
source share
2 answers

I think the easiest way is to use the NSThread method - (void) cancel . You will need a link to the created stream. Your sample code will look something like this if you can make the workflow look like 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 flow between loop iterations. So, if you are doing a long lock calculation, you will have to find a way to break it into pieces so that you can periodically check isCancelled.

+12
source share

Also consider the NSOperation and NSOperationQueue classes. This is another set of thread classes that make developing a workflow model very easy.

+2
source share

All Articles