How to pause/continue NSThread - objective-c

I have an app, where i use function FSMoveObjectToTrashSync. It works in background thread. I need ability for my app, to click on button to pause it or continue(if it paused) how i can make it?
Example of code:
NSMutableArray *fileArray = [NSMutableArray array withobjects:#"file1url", #"file2", #"file3", nil];
NSMutableArray *threadArray = [[NSMutableArray alloc] init];
-(void)myFunc{
for (NSURL *url in fileArray){
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:#selector(mySelectorWith:) object:url];
[thread start];
[threadArray addObject:thread];
}
}
-(void)mySelectorWith:(NSURL *) url{
FSRef source;
FSPathMakeRef((const UInt8 *)[[url path] fileSystemRepresentation], &source, NULL);
FSMoveObjectToTrashSync(&source, NULL, kFSFileOperationDefaultOptions);
}
PS:sorry for my english, i'm from Belarus... =(

One solution would be to replace the for loop on a single thread with an NSOperation subclass. Each operation should trash exactly one object; you then create one operation for each object you want to trash and put all of the operations on an NSOperationQueue.
The operation queue will run each operation on a thread, and it can even run multiple operations on multiple threads if it sees enough computing power laying around to do it.
An operation queue can be paused and resumed at will; when you suspend the queue, any operations in that queue that are already running will finish, but no more will start until you resume the queue.

You could use an NSConditionLock. An NSConditionLock is similar to a condition variable. It has a couple of basic methods, lockWhenCondition, and unlockWithCondition, and lock. A typical usage is to have your background thread waiting on the condition lock with "lockWhenCondition:", and the in you foreground thread to set the condition, which causes the background thread to wake up. The condition is a simple integer, usually an enumeration.
Here's an example:
enum {
kWorkTodo = 1,
kNoWorkTodo = 0
}
- (id)init {
if ((self = [super init])) {
theConditionLock = [[NSConditionLock alloc] initWithCondition: kNoWorkTodo];
workItems = [[NSMutableArray alloc] init];
}
}
- (void)startDoingWork {
[NSThread detachNewThreadSelector:#selector(doBackgroundWork) toTarget:self withObject:nil];
}
- (void)doBackgroundWork:(id)arg {
while (YES) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSArray *items = nil;
[theConditionLock lockWhenCondition:kWorkTodo]; // Wait until there is work to do
items = [NSArray arrayWithArray:workItems]
[workItems removeAllObjects];
[theConditionLock unlockWithCondition:kNoWorkTodo];
for(id item in items) {
// Do some work on item.
}
[pool drain];
}
}
- (void)notifyBackgroundThreadAboutNewWork {
[theConditionLock lock];
[workItems addObject:/* some unit of work */];
[theConditionLock unlockWithCondition:kWorkTodo];
}
In this example, when startDoingWork is called doBackgroundWork: will start on a background thread, but then stop because there isn't any work to do. Once notifyBackgroundThreadAboutNewWork is called, then doBackgroundWork: will fire up and process the new work, and then go back to sleep waiting for new work to be available, which will happen the next time notifyBackgroundThreadAboutNewWork is called.

Related

Calling performSelector:onThread:withObject:waitUntilDone: more than once on same thread results in delay

For code like:
// Code in some object that will do work for an application:
- (BOOL)shouldBeRunning
{
[lockRunning lock];
BOOL shouldBeRunning= shouldRun;
[lockRunning unlock];
return shouldBeRunning;
}
- (void)stopRunning
{
[lockRunning lock];
shouldRun= FALSE;
[lockRunning unlock];
}
- (void)threadEntryPoint:(id)object
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
// From an example I saw awhile back:
// A runloop with no sources returns immediately from runMode:beforeDate:
// That will wake up the loop and chew CPU. Add a dummy source to prevent it.
NSMachPort *dummyPort = [[NSMachPort alloc] init];
[runLoop addPort:dummyPort forMode:NSDefaultRunLoopMode];
[dummyPort release];
[pool release];
while ([self shouldBeRunning])
{
NSAutoreleasePool *loopPool = [[NSAutoreleasePool alloc] init];
[runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
[loopPool drain];
}
}
- (BOOL)startRunning:(NSError **)errorPtr
{
[self stopRunning]; // Stop if we are already running.
[runWorker release];
runWorker= [[NSThread alloc] initWithTarget:self selector:#selector(threadEntryPoint:) object:nil];
if(!runWorker)
return (FALSE);
// Start up the thread.
shouldRun= TRUE;
[runWorker start];
return TRUE;
}
- (void)doLotsOfStuff
{
// Some operation that is long and intensive
// that should be done in the background.
// This function will call the app delegate, which will display the
// results. It will also notify the app on completion.
}
- (void)doStuff
{
// Commented out for illustrative purposes.
//[self startRunning]; // Fire thread up.
[self performSelector:#selector(doLotsOfStuff) onThread:runWorker withObject:nil waitUntilDone:NO];
}
// Out in the delegate:
- (void)applicationDidFinishLaunching:(NSNotification*)aNotification
{
// Do setup....
[workObject startRunning]; // Start the worker thread in the worker object.
}
- (void)buttonHandler:(id)sender
{
[workObject doStuff];
}
So, in the application there is a button. The user will press it, and a task will run on a worker thread. The task will provide feedback to the application. In this case, the button is disabled until the task completes. I just do not want to show all that code.
With the code as written, if I press the button once, the task runs without delay. Often, a second button press yields the same result. However, sometimes the second press, but almost always the third or after, will result in a significant delay in performing the task. I put debug statements in and can observe that the code does the performSelector on the thread, then there is a delay, and finally the task runs.
If I uncomment the line in doStuff that re-creates the thread (making the one in applicationDidFinishLaunching redundant), of course it works perfectly every time.
From what I can tell, the thread is getting into an unresponsive state.
Any ideas on what might be going on? Anything obviously wrong with the setup and handling code? Any input appreciated.

Why is nsoperation working serially?

I am using the following code for nsoperation.The problem is all three tasks run serially.What can I do to make the tasks run in parallel.I tried implementing the start and isconcurrent methods but it doesnt work.please help...
Given is my uaview controller class
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
Store *S=[ [Store alloc] init];
S.a=25;
NSOperationQueue *someQueue = [NSOperationQueue currentQueue];
someQueue.MaxConcurrentOperationCount = 3;
NSInvocationOperation *invocationOp2 = [[NSInvocationOperation alloc] initWithTarget:self
selector:#selector(ymain)
object:nil];
NSInvocationOperation *invocationOp3 = [[NSInvocationOperation alloc] initWithTarget:self
selector:#selector(ymain2)
object:nil];
NSInvocationOperation *invocationOp4 = [[NSInvocationOperation alloc] initWithTarget:self
selector:#selector(ymain3)
object:nil];
[someQueue addOperation:invocationOp2];
[someQueue addOperation:invocationOp3];
[someQueue addOperation:invocationOp4];
}
-(void)ymain
{
for (int i = 0 ; i < 10000 ; i++) {
NSLog(#"in the A main"); }
}
This is the other class which was subclassed
#interface A : NSOperation
#end
#implementation A
bool executing;
bool finished;
-(void)main
{
}
- (BOOL)isConcurrent
{
return YES;
}
- (BOOL)isReady
{
return YES;
}
currentQueue is returning the main queue, which is a serial queue that executes on the main runloop. You should create your own NSOperationQueue to run the operations concurrently.
NSOperationQueue manages the number of operations depending on various factors. This is an implementation detail which you cannot effect. You cannot force it to perform operations concurrently.
The only influence you can have is to set operation dependancy, which affects the order in which operations are performed serially (which isn't much use to you!)
Also currentQueue will return nil when it is called from outside of an NSOperation. If you use mainQueue then you'll get the queue which always runs on the main thread and only runs one operation at one. You need to create a new queue.

Pre-empting NSOperation on one NSOperationQueue with NSOperation placed onto a separate NSOperationQueue?

I have an application in which a long running process (> 1 min) is placed onto an NSOperationQueue (Queue A). The UI is fully-responsive while the Queue A operation runs, exactly as expected.
However, I have a different kind of operation the user can perform which runs on a completely separate NSOperationQueue (Queue B).
When a UI event triggers the placement of an operation on Queue B, it must wait until after the currently-executing operation on Queue A finishes. This occurs on an iPod Touch (MC544LL).
What I expected to see instead was that any operation placed onto Queue B would more or less begin immediately executing in parallel with the operation on Queue A. This is the behavior I see on the Simulator.
My question is two parts:
Is the behavior I'm seeing on my device to be expected based on available documentation?
Using NSOperation/NSOperationQueue, how do I pre-empt the currently running operation on Queue A with a new operation placed on Queue B?
Note: I can get exactly the behavior I'm after by using GCD queues for Queues A/B, so I know my device is capable of supporting what I'm trying to do. However, I really, really want to use NSOperationQueue because both operations need to be cancelable.
I have a simple test application:
The ViewController is:
//
// ViewController.m
// QueueTest
//
#import "ViewController.h"
#interface ViewController ()
#property (strong, nonatomic) NSOperationQueue *slowQueue;
#property (strong, nonatomic) NSOperationQueue *fastQueue;
#end
#implementation ViewController
-(id)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super initWithCoder:aDecoder]) {
self.slowQueue = [[NSOperationQueue alloc] init];
self.fastQueue = [[NSOperationQueue alloc] init];
}
return self;
}
-(void)viewDidLoad
{
NSLog(#"View loaded on thread %#", [NSThread currentThread]);
}
// Responds to "Slow Op Start" button
- (IBAction)slowOpStartPressed:(id)sender {
NSBlockOperation *operation = [[NSBlockOperation alloc] init];
[operation addExecutionBlock:^{
[self workHard:600];
}];
[self.slowQueue addOperation:operation];
}
// Responds to "Fast Op Start" button
- (IBAction)fastOpStart:(id)sender {
NSBlockOperation *operation = [[NSBlockOperation alloc] init];
[operation addExecutionBlock:^{
NSLog(#"Fast operation on thread %#", [NSThread currentThread]);
}];
[self.fastQueue addOperation:operation];
}
-(void)workHard:(NSUInteger)iterations
{
NSLog(#"SlowOperation start on thread %#", [NSThread currentThread]);
NSDecimalNumber *result = [[NSDecimalNumber alloc] initWithString:#"0"];
for (NSUInteger i = 0; i < iterations; i++) {
NSDecimalNumber *outer = [[NSDecimalNumber alloc] initWithUnsignedInteger:i];
for (NSUInteger j = 0; j < iterations; j++) {
NSDecimalNumber *inner = [[NSDecimalNumber alloc] initWithUnsignedInteger:j];
NSDecimalNumber *product = [outer decimalNumberByMultiplyingBy:inner];
result = [result decimalNumberByAdding:product];
}
result = [result decimalNumberByAdding:outer];
}
NSLog(#"SlowOperation end");
}
#end
The output I see after first pressing the "Slow Op Start" button followed ~1 second later by pressing the "Fast Op Start" button is:
2012-11-28 07:41:13.051 QueueTest[12558:907] View loaded on thread <NSThread: 0x1d51ec30>{name = (null), num = 1}
2012-11-28 07:41:14.745 QueueTest[12558:1703] SlowOperation start on thread <NSThread: 0x1d55e5f0>{name = (null), num = 3}
2012-11-28 07:41:25.127 QueueTest[12558:1703] SlowOperation end
2012-11-28 07:41:25.913 QueueTest[12558:3907] Fast operation on thread <NSThread: 0x1e36d4c0>{name = (null), num = 4}
As you can see, the second operation does not begin executing until after the first operation finishes, despite the fact that these are two separate (and presumably independent) NSOperationQueues.
I have read the Apple Concurrency Guide, but find nothing describing this situation. I've also read two SO questions on related topics (link, link), but neither seems to get to the heart of the problem I'm seeing (pre-emption).
Other things I've tried:
setting the queuePriority on each NSOperation
setting the queuePriority on each NSOperation while placing both types of operations onto the same queue
placing both operations onto the same queue
This question has undergone multiple edits, which may make certain comments/answers difficult to understand.
I suspect the problem you are having is that both operation queues are executing their blocks on the underlying default priority dispatch queue. Consequently, if several slow operations are enqueued before the fast operations then perhaps you will see this behaviour.
Why not either set the NSOperationQueue instance for the slow operations so that it only executes one operation at any given time (i.e. set maxConcurrentOperationCount to one for this queue), or if your operations are all blocks then why not use GCD queues directly? e.g.
static dispatch_queue_t slowOpQueue = NULL;
static dispatch_queue_t fastOpQueue = NULL;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
slowOpQueue = dispatch_queue_create("Slow Ops Queue", NULL);
fastOpQueue = dispatch_queue_create("Fast Ops Queue", DISPATCH_QUEUE_CONCURRENT);
});
for (NSUInteger slowOpIndex = 0; slowOpIndex < 5; slowOpIndex++) {
dispatch_async(slowOpQueue, ^(void) {
NSLog(#"* Starting slow op %d.", slowOpIndex);
for (NSUInteger delayLoop = 0; delayLoop < 1000; delayLoop++) {
putchar('.');
}
NSLog(#"* Ending slow op %d.", slowOpIndex);
});
}
for (NSUInteger fastBlockIndex = 0; fastBlockIndex < 10; fastBlockIndex++) {
dispatch_async(fastOpQueue, ^(void) {
NSLog(#"Starting fast op %d.", fastBlockIndex);
NSLog(#"Ending fast op %d.", fastBlockIndex);
});
}
As far as using the NSOperationQueue as per your comments about needing the operation cancellation facilities etc. can you try:
- (void)loadSlowQueue
{
[self.slowQueue setMaxConcurrentOperationCount:1];
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
NSLog(#"begin slow block 1");
[self workHard:500];
NSLog(#"end slow block 1");
}];
NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(#"begin slow block 2");
[self workHard:500];
NSLog(#"end slow block 2");
}];
[self.slowQueue addOperation:operation];
[self.slowQueue addOperation:operation2];
}
As I think the two blocks you add to the operation on the slow queue are being executed in parallel on the default queue and preventing your fast operations from being scheduled.
Edit:
If you're still finding the default GCD queue is choking, why not create an NSOperation subclass that executes blocks without using GCD at all for your slow operations, this will still give you the declarative convenience of not creating a separate subclass for each operation but use the threading model of a regular NSOperation. e.g.
#import <Foundation/Foundation.h>
typedef void (^BlockOperation)(NSOperation *containingOperation);
#interface PseudoBlockOperation : NSOperation
- (id)initWithBlock:(BlockOperation)block;
- (void)addBlock:(BlockOperation)block;
#end
And then for the implementation:
#import "PseudoBlockOperation.h"
#interface PseudoBlockOperation()
#property (nonatomic, strong) NSMutableArray *blocks;
#end
#implementation PseudoBlockOperation
#synthesize blocks;
- (id)init
{
self = [super init];
if (self) {
blocks = [[NSMutableArray alloc] initWithCapacity:1];
}
return self;
}
- (id)initWithBlock:(BlockOperation)block
{
self = [self init];
if (self) {
[blocks addObject:[block copy]];
}
return self;
}
- (void)main
{
#autoreleasepool {
for (BlockOperation block in blocks) {
block(self);
}
}
}
- (void)addBlock:(BlockOperation)block
{
[blocks addObject:[block copy]];
}
#end
Then in your code you can do something like:
PseudoBlockOperation *operation = [[PseudoBlockOperation alloc] init];
[operation addBlock:^(NSOperation *operation) {
if (!operation.isCancelled) {
NSLog(#"begin slow block 1");
[self workHard:500];
NSLog(#"end slow block 1");
}
}];
[operation addBlock:^(NSOperation *operation) {
if (!operation.isCancelled) {
NSLog(#"begin slow block 2");
[self workHard:500];
NSLog(#"end slow block 2");
}
}];
[self.slowQueue addOperation:operation];
Note that in this example any blocks that are added to the same operation will be executed sequentially rather than concurrently, to execute concurrently create one operation per block. This has the advantage over NSBlockOperation in that you can pass parameters into the block by changing the definition of BlockOperation - here I passed the containing operation, but you could pass whatever other context is required.
Hope that helps.

MailCore concurrency support

I'm developing a mail client using the MailCore framework (based on the C library LibEtPan). I'd like to handle the server connection and all the requests in new thread or queue and pushing informations to the main queue for UI updates.
The problem it seems that MailCore variables can't be shared across threads.
#implementation Controller
{
NSOperationQueue *_queue;
CTCoreAccount *_account;
CTCoreFolder *_inbox;
NSArray *_messages;
}
- (id)init
{
// stuff
_queue = [[NSOperationQueue alloc] init];
[_queue addOperationWithBlock:^
{
_account = [[CTCoreAccount alloc] init];
BOOL success = [_account connectToServer:#"imap.mail.com" port:993 connectionType:CTConnectionTypeTLS authType:CTImapAuthTypePlain login:#"me#mail.com" password:#"Password"];
if (success)
{
CTCoreFolder *inbox = [_account folderWithPath:#"INBOX"];
NSArray *messages = [inbox messagesFromSequenceNumber:1 to:0 withFetchAttributes:CTFetchAttrEnvelope];
[[NSOperationQueue mainQueue] addOperationWithBlock:^
{
_messages = [messages copy];
// UI updates here
}];
}
}];
// Other stuff
}
Later, for example this method could be called :
- (void)foo
{
[_queue addOperationWithBlock:^
{
CTCoreMessage *message = [_messages objectAtIndex:index];
BOOL isHTML;
NSString *body = [message bodyPreferringPlainText:&isHTML];
[[NSOperationQueue mainQueue] addOperationWithBlock:^
{
// UI Updates
}];
}];
}
Here, body is empty because CTCore variables are unable to execute new requests from _queue.
According to this comment, each thread needs is own CTCoreAccount, etc ...
Threads on iOS are supposed to have shared memory. I don't exactly understand why reusing the same CTCoreAccount across threads doesn't work, even if references are used in the LibetPan library.
How to define a unique CTCoreAccount or CTCoreFolder "attached" to a different thread or queue that can be reused multiple times ?
Any advise would be appreciated. Thank you.
The answer has been given by MRonge here.
One way is to create an object that contains both the NSOperationQueue
(with the maxConcurrentOperationCount=1) and the CTCoreAccount. All
work for that account goes through the object, and is only executed on
one thread at a time. Then you can one of these objects for each
account you want to access.

Receiving memory warning when using performSelectorInBackground

I have a UITableView that, when items are selected, loads a viewController, which inside it performs some operations in the background using performSelectorInBackground.
Everything works fine if you slowly tap items in the tableView (essentially allowing the operations preforming in background to finish). But when you select the items quickly, the app quickly returns some memory warnings until it crashes, usually after about 7 or 8 "taps" or selections.
Any idea why this would be? When I move my code from the background thread to the main thread, everything works fine as well. You just can't make the tableView selections as quickly because it's waiting for the operations to finish.
Code snippets:
//this is called from - (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
-(void) showLeaseView:(NSMutableDictionary *)selLease
{
LeaseDetailController *leaseController = [[LeaseDetailController alloc] initWithNibName:#"LeaseDetail" bundle:nil];
leaseController.lease = selLease;
//[leaseController loadData];
[detailNavController pushViewController:leaseController animated:NO];
[leaseController release];
}
//this is in LeaseDetailController
- (void)viewDidLoad {
[self performSelectorInBackground:#selector(getOptions) withObject:nil];
[super viewDidLoad];
}
-(void) getOptions
{
NSAutoreleasePool *apool = [[NSAutoreleasePool alloc] init];
NSArray *arrayOnDisk = [[NSArray alloc] initWithContentsOfFile:[appdel.settingsDir stringByAppendingPathComponent:#"optionData"]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"(LEASE_ID contains[cd] %#)", [lease leaseId]];
self.options = [NSMutableArray arrayWithArray:[arrayOnDisk filteredArrayUsingPredicate:predicate]];
[arrayOnDisk release];
[apool release];
}
Every time you perform the getOptions selector in the background, what's really happening is a new thread is being created on your behalf, and the work is being done there. When the user taps your table cells a bunch of times in a row, a new thread is created each time to handle the work. If the work done by getOptions takes some time to complete, you will have multiple threads calling getOptions at the same time. That is to say, the system doesn't cancel previous requests to perform getOptions in the background.
If you assume that it takes N bytes of memory to perform the work done by getOptions, then if the user taps on five table cells in a row and getOptions doesn't finish right away, then you'll find that your app is using 5 * N bytes at that point. In contrast, when you change your app to call getOptions on the main thread, it has to wait for each call to getOptions to complete before it can call getOptions again. Thus when you do your work on the main thread you don't run into the situation where you're using 5 * N bytes of memory to do the work of five instances of getOptions simultaneously.
That's why you run out of memory when you do this work in the background and the user taps multiple table cells: you're doing multiple instances of the work, and each instance requires its own amount of memory, and when they all get added up, it's more than the system can spare.
It looks like you're just calling getOptions once when the user selects a table cell and navigates into a new view controller. Since the user will only be looking at one of these view controllers at a time, you don't really need to have multiple instances of getOptions going on simultaneously in the background. Instead, you want to cancel the previously-running instance before starting the new one. You can do this using an NSOperationQueue, like so:
- (NSOperationQueue *)operationQueue
{
static NSOperationQueue * queue = nil;
if (!queue) {
// Set up a singleton operation queue that only runs one operation at a time.
queue = [[NSOperationQueue alloc] init];
[queue setMaxConcurrentOperationCount:1];
}
return queue;
}
//this is called from - (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
-(void) showLeaseView:(NSMutableDictionary *)selLease
{
LeaseDetailController *leaseController = [[LeaseDetailController alloc] initWithNibName:#"LeaseDetail" bundle:nil];
leaseController.lease = selLease;
// Cancel any pending operations. They'll be discarded from the queue if they haven't begun yet.
// The currently-running operation will have to finish before the next one can start.
NSOperationQueue * queue = [self operationQueue];
[queue cancelAllOperations];
// Note that you'll need to add a property called operationQueue of type NSOperationQueue * to your LeaseDetailController class.
leaseController.operationQueue = queue;
//[leaseController loadData];
[detailNavController pushViewController:leaseController animated:NO];
[leaseController release];
}
//this is in LeaseDetailController
- (void)viewDidLoad {
// Now we use the operation queue given to us in -showLeaseView:, above, to run our operation in the background.
// Using the block version of the API for simplicity.
[queue addOperationWithBlock:^{
[self getOptions];
}];
[super viewDidLoad];
}
-(void) getOptions
{
NSAutoreleasePool *apool = [[NSAutoreleasePool alloc] init];
NSArray *arrayOnDisk = [[NSArray alloc] initWithContentsOfFile:[appdel.settingsDir stringByAppendingPathComponent:#"optionData"]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"(LEASE_ID contains[cd] %#)", [lease leaseId]];
NSMutableArray * resultsArray = [NSMutableArray arrayWithArray:[arrayOnDisk filteredArrayUsingPredicate:predicate]];
// Now that the work is done, pass the results back to ourselves, but do so on the main queue, which is equivalent to the main thread.
// This ensures that any UI work we may do in the setter for the options property is done on the right thread.
dispatch_async(dispatch_queue_get_main(), ^{
self.options = resultsArray;
});
[arrayOnDisk release];
[apool release];
}