GCD dispatch_async for app-lifetime task? - objective-c

I've used GCD before with dispatch_async for background-threading units of work like parsing data from a network request (in, say, JSON or XML), and it's WONDERFUL. But what if I have a background task that's going to run for the length of the application? Is dispatch_async still a good fit for this case, or is there a better way to implement it?

Sure, but create your own dispatch queue for it. (If you use a global queue, you may tie up that queue--or one of its threads--forever.)
dispatch_queue_t dispatchQueue = dispatch_queue_create("com.mycompany.myapp.ForeverOperation", DISPATCH_QUEUE_SERIAL);
dispatch_async(dispatchQueue, ^{
// worker routine
});
More traditionally, you would create an explicit thread for this, and if it will run forever, that might make more "sense". But the results are basically the same.
NSThread * myWorkerThread = [[NSThread alloc] initWithTarget:...
[myWorkerThread start];
If you need to communicate with other threads/queues, as always, standard synchronization techniques may be required.

This really has nothing to do with dispatch_async, which is merely one approach to doing something in a background thread. If you want to do something in a background thread, do it in a background thread! Just be aware that doing this constantly can be a drag on your app, since you've only got so much processing time and only so many processors; you may end up having to study that in Instruments. You might want to break up your task into little bits and do it in short chunks every so often. Both GCD and NSOperation can help with that.

Related

Sending code to the background, waiting, then going back to the main thread without blocking?

A common pattern in Objective C is to run a bit of code in a background thread, then go back to the main thread to make UI adjustments. If the code starts in the main thread, I'd attack this with a pattern like so:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self someBackgroundTask];
dispatch_async(dispatch_get_main_queue(), ^{
[self someUITask];
});
});
However, this seems like a really clunky way to do it, not in the least because it creates two levels of nesting that feeling unnecessary. Is there a better way to do this? Note that the UI code is considered in this instance to be relying on the background task completing, so it can't just be dropped after the first dispatch.
Just move all the threading stuff into someBackgroundTask:
[self someBackgroundTaskWithCompletion:^{
[self someUITask];
}];
Then do your dispatch_async() stuff inside the background task method.
Conceptually, you need to run code on two different threads. All UI operations must run on the main thread, and your blocking operation needs to run on a background thread. At the absolute minimum this would require two lines of code.
GCD makes this fairly simple as you mentioned; I'm not sure any language would have a better way to handle this core issue. Sure, the block syntax is bad (http://fuckingblocksyntax.com); but the core fundamentals are pretty solid.
If the nesting bothers you, try moving all that UI code to a different method, and calling that method from your second nested block. You could even create a method that accepts a 'backgroundWork' selector/block and a 'foregroundWork' selector/block. However - I'd argue that the typical UI work you'd perform in such a case would be very minimal, making the extra nesting a minor inconvenience rather than an actual problem.
As far as asynchronous blocks of code that are inter-dependent, check out PromiseKit or even Sequencer; both are good options for supplementing one of Objective C's primary weakness (sequentially performed multi-threaded operations).
I haven't used it myself, but I understand that Facebook/Parse have also released another solution called BFTask, part of the Bolts framework: https://github.com/BoltsFramework/Bolts-iOS
(Or just use C#)

convert pthread to objective-c

Im trying to convert the following to objective-c code.
This is the current thread I have in C and works fine
//calling EnrollThread method on a thread in C
pthread_t thread_id;
pthread_create( &thread_id, NULL, EnrollThread, pParams );
//What the EnrollThread method structure looks like in C
void* EnrollThread( void *arg )
What my method structure looks like now that I've changed it to objective-c
-(void)enrollThreadWithParams:(LPBIOPERPARAMS)params;
Now I'm not sure how to call this objective-c method with the pthread_create call.
I've tried something like this:
pthread_create( &thread_id, NULL, [refToSelf enrollThreadWithParams:pParams], pParams );
But I believe I have it wrong. Can anyone enlighten me on why this does not work and what it is I need to do to fix it so that I can create my thread in the background? My UI is getting locked until the method finishes what it's doing.
I was thinking of also using dispatch_sync but I haven't tried that.
In objective C you don't really use pthread_create, although you can still use it, but the thread entry point needs to be a C function, so I'm not sure if this would be the best approach.
There are many options, as you can read in the Threading and Concurrency documents.
performSelectorInBackground method of NSObject (and subclasses)
dispatch_async (not dispatch_sync as you mentioned)
NSOperation and NSOperationQueue
NSThread class
I would suggest giving it a shot to the first one, since it is the easiest, and very straightforward, also the second one is very easy because you don't have to create external objects, you just place inline the code to be executed in parallel.
The go to reference for concurrent programming is the Concurrency Programming Guide which walks you through dispatch queues (known as Grand Central Dispatch, GCD) and operation queues. Both are incredibly easy to use and offer their own respective advantages.
In their simplest forms, both of these are pretty easy to use. As others have pointed out, the process for creating a dispatch queue and then dispatching something to that queue is:
dispatch_queue_t queue = dispatch_queue_create("com.domain.app", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
// something to do in the background
});
The operation queue equivalent is:
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperationWithBlock:^{
// something to do in the background
}];
Personally, I prefer operation queues where:
I need controlled/limited concurrency (i.e. I'm going to dispatch a bunch of things to that queue and I want them to run concurrent with respect to not only the main queue, but also with respect to each other, but I don't want more than a few of those running simultaneously). A good example would be when doing concurrent network requests, where you want them running concurrently (because you get huge performance benefit) but you generally don't want more than four of them running at any given time). With an operation queue, one can specify maxConcurrentOperationCount whereas this tougher to do with GCD.
I need fine level of control over dependencies. For example, I'm going to start operations A, B, C, D, and E, but B is dependent on A (i.e. B shouldn't start before A finishes), D is dependent upon C, and E is dependent upon both B and D finishing.
I need to enjoy concurrency on tasks that, themselves, run asynchronously. Operations offer a fine degree of control over what determines when the operation is to be declared as isFinished with the use of NSOperation subclass that uses "concurrent operations". A common example is the network operation which, if you use the delegate-based implementation, runs asynchronously, but you still want to use operations to control the flow of one to the next. The very nice networking library, AFNetworking, for example, uses operations extensively, for this reason.
On the other hand, GCD is great for simple one-off asynchronous tasks (because you can avail yourself of built-in "global queues", freeing yourself from making your own queue), serial queues for synchronizing access to some shared resource, dispatch sources like timers, signaling between threads with semaphores, etc. GCD is generally where people get started with concurrent programming in Cocoa and Cocoa Touch.
Bottom line, I personally use operation queues for application-level asynchronous operations (network queues, image processing queues, etc.), where the degree of concurrency becomes and important issue). I tend to use GCD for lower-level stuff or quick and simple stuff. GCD (with dispatch_async) is a great place to start as you dip your toe into the ocean of concurrent programming, so go for it.
There are two things I'd encourage you to be aware of, regardless of which of these two technologies you use:
First, remember that (in iOS at least) you always want to do user interface tasks on the main queue. So the common patterns are:
dispatch_async(queue, ^{
// do something slow here
// when done, update the UI and model objects on the main queue
dispatch_async(dispatch_get_main_queue(), ^{
// UI and model updates can go here
});
});
or
[queue addOperationWithBlock:^{
// do something slow here
// when done, update the UI and model objects on the main queue
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
// do UI and model updates here
}];
}];
The other important issue to consider is synchronization and "thread-safety". (See the Synchronization section of the Threading Programming Guide.) You want to make sure that you don't, for example, have the main thread populating some table view while, at the same time, some background queue is changing the data used by that table view at the same time. You want to make sure that while any given thread is using some model object or other shared resource, that another thread isn't mutating it, leaving it in some inconsistent state.
There's too much to cover in the world of concurrent programming. The WWDC videos (including 2011 and 2012) offer some great background on GCD and asynchronous programming patterns, so make sure you avail yourself of that great resource.
If you already have working code, there is no reason to abandon pthreads. You should be able to use it just fine.
If, however, you want an alternative, but you want to keep your existing pthread entry point, you can do this easily enough...
dispatch_queue_t queue = dispatch_queue_create("EnrollThread", DISPATCH_QUEUE_SERIAL);
dispatch_async(queue, ^{
EnrollThread(parms);
});

Executing two functions in exactly the same time

im pretty new in Obj-C, and im wondering how to execute two functions in exactly the same time(with an accuracy to 1ms) without waiting for return, on different theards.
Currently i tried with
#define kBgQueue1 dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)
dispatch_sync(kBgQueue1, ^{
[self function1];
});
dispatch_sync(kBgQueue1, ^{
[self function2];
});
dispatch_get_global_queue() gives you a concurrent queue, which can execute
tasks in parallel. But you have to use
dispatch_async() to execute the blocks without waiting for them to complete.
Note however that Grand Central Dispatch makes no guarantee about the timing.
Also GCD uses a limited thread pool, so there is also no guarantee that
the blocks are executed "simultaneously".
If you need more control about the thread creation then you would have to use lower-level classes/functions
such as NSThread or pthread_create().
As #Volker already said in a comment, you don't have 100% control over the
timing on OS X or iOS.
For more information, see the "Concurrency Programming Guide".

NSOperation to all run consequently

I have program that is crashing somewhere not really visible to programmer. It may have something to do with memory management but it definitively has something to do with multiple threads and more than 200 notification observers...
I would like to know if that kind of starting derived NSOperation object would ensure that all operations are being executed consequently as normal execution on one thread?
[operation start];
[operation waitUntilFinished];
I think what you're looking for is operationQueue.maxConcurrentOperationCount = 1 and then add all your operations to the NSOperationQueue. They will be executed serially, one after another.
No, it starts the operation and then blocks the calling thread until it is done.

Threading in Objective-C

Are there threads in Objective C? If so, how are they declared and used?
If anybody knows about multithreading in Objective C, please share with me.
Thanks and regards.
An easy way to just spin off a method in a new thread is to use.
+ (void)detachNewThreadSelector:(SEL)aSelector toTarget:(id)aTarget withObject:(id)anArgument on NSThread. If you aren't running garbage collected you need to set up your own autorelease pool.
Another easy way if you just don't want to block the main thread is to use.
- (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg on NSObject
Depending on what type of concurrency you are after you should also take a look at NSOperation that can give you free locking so you can share it between several threads among other things.
If you're developing using Cocoa (ie for the mac or iphone), you have access to the NSThread class, which can be used for multithreading. Googling for NSThread will find you the API.
You can declare it like using:
NSThread *mythread = [[NSThread alloc] initWithTarget:target selector:selector object:argument];
Where target and selector is the object and selector you want to start a thread with, and argument is an argument to send to the selector.
Then use [mythread start] to start it.
Yes there are threading concepts in Objective C. and there are multiple way to achieve multi threading in objective C.
1> NSThread
[NSThread detachNewThreadSelector:#selector(startTheBackgroundJob) toTarget:self withObject:nil];
This will create a new thread in the background. from your main thread.
2> Using performSelector
[self.tableView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:YES];
will perform UI task on your main thread if you call this from background thread... You can also use
[self performSelectorInBackground:#selector(abc:) withObject:obj];
Which will create a background thread.
3> Using NSoperation
Follow this link
4> Using GCD
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self callWebService];
dispatch_async(dispatch_get_main_queue(), ^{
[self updateUI];
});
});
Will callWebService in background thread and once it's completed. It will updateUI in main thread.More about GCD
This is almost all way of multithreading that is used in iOS. hope this helps.
You could also look into NSOperation
To see an example of this, have a look at Drew McCormack's post on MacResearch.
Before going to far with stuff like detachNewThreadSelector: be sure to check out Apple's official documentation. For a high-level overview of options (including operation queues, dispatch queues, and such), there's the Concurrency Programming Guide. And, for a look at lower-level (and less recommended) threading, there's the Threading Programming Guide.
You definitely don't want to just start spinning up threads without reading what Apple has to say on the subject first. They've done a lot of work with stuff like GCD to make it easier and safer to write concurrent programs.