GCD flow how to write - iphone

I am trying to make screen shot of avplayer when video start playing so i need to run this code in fast in background so it will not block main thread and other controls run fast simultaneous,trying to run that code GCD format i am not able to run please help me to do that it stops at where i add into my array(in array i am adding UIImage Object)...
if (isCaptureScreenStart)
{
if (CMTimeGetSeconds([avPlayer currentTime])>0)
{
if (avFramesArray!=nil)
{
queue = dispatch_queue_create("array", NULL);
dispatch_sync(queue, ^{
[avFramesArray addObject:[self screenshotFromPlayer:avPlayer maximumSize:avPlayerLayer.frame.size :CMTimeGetSeconds([avPlayer currentTime])]];//stop at this line
NSLog(#"count:%d",[avFramesArray count]);
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(#"Frame are created:%d",[avFramesArray count]);
if ([avFramesArray count]==0)
{
NSLog(#"Frame are over");
}
});
});
}
}
}
dispatch_release(queue);
Edit:
I think i need to use dispatch_group_async this block now..please give some guideline that how to use:
if (isCaptureScreenStart)
{
if (CMTimeGetSeconds([avPlayer currentTime])>0)
{
if (avFramesArray!=nil) {
dispatch_group_async(serial_group1, serial_dispatch_queue1, ^{
[avFramesArray addObject:[self screenshotFromPlayer:avPlayer maximumSize:avPlayerLayer.frame.size :CMTimeGetSeconds([avPlayer currentTime])]];
});
}
}
dispatch_group_notify(serial_group1, serial_dispatch_queue1, ^{
NSLog(#"task competed");
});
}
Now I am using this block but above execution is contentious running and if i use dispatch_suspend(serial_dispatch_queue1); its stop but again i need to start block execution then what i need to use i have also try with dispatch_resume(serial_dispatch_queue1); again load but system show me crash

dispatch_release(queue); don't do it there, the dispatch queue that you are calling its going to a backThread, so wat is happening is :-
your queue is getting released before the block of code executes.
since your queue looks like an ivar, release it in dealloc. Rest, your code looks fine ..put a breakpoint inside and check if the block is executing.
EDIT
I dont understand, what u are trying to achieve by suspending the queue, there is no need to do it. You dont need to check whether the block has finished executing. The block will finish and then call the dispatch_async , get the main queue and update the UI from there.
Now, when you are creating the queue, create it lazily in your method. take the queue as an ivar in header file:
#interface YourFileController : UIViewController {
dispatch_queue_t queue;
}
Then in your method modify it as such:
if (isCaptureScreenStart)
{
if (CMTimeGetSeconds([avPlayer currentTime])>0)
{
if (avFramesArray!=nil)
{
if (!queue)
queue = dispatch_queue_create("array", DISPATCH_QUEUE_SERIAL);
dispatch_sync(queue, ^{
[avFramesArray addObject:[self screenshotFromPlayer:avPlayer maximumSize:avPlayerLayer.frame.size :CMTimeGetSeconds([avPlayer currentTime])]];//stop at this line
NSLog(#"count:%d",[avFramesArray count]);
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(#"Frame are created:%d",[avFramesArray count]);
if ([avFramesArray count]==0)
{
NSLog(#"Frame are over");
}
});
});
}
}
}
NOTE : DISPATCH_QUEUE_SERIAL creates a serial queue, meaning all the blocks submitted to it will execute serially in First in First Out order. Once all the blocks submitted get executed, the queue stays ;) ..submit another block to it and it executes the block :D
this represents one whole block:-
[avFramesArray addObject:[self screenshotFromPlayer:avPlayer maximumSize:avPlayerLayer.frame.size :CMTimeGetSeconds([avPlayer currentTime])]];//stop at this line
NSLog(#"count:%d",[avFramesArray count]);
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(#"Frame are created:%d",[avFramesArray count]);
if ([avFramesArray count]==0)
{
NSLog(#"Frame are over");
}
});

Related

Updating label on the main thread is not working

I'm trying to update a label while different tasks are proceeding. I searched and used different options and endup using this way but it still doesn't work:
[processStatusLable performSelectorOnMainThread:#selector(setText:) withObject:#"Creating your account..." waitUntilDone:NO];
DCConnector *dccon = [DCConnector new];
ContactsConnector *conCon = [ContactsConnector new];
if (![dccon existUsersData]) {
[dccon saveUsersInformation:device :usDTO];
//created account
//get friends -> Server call
[processStatusLable performSelectorOnMainThread:#selector(setText:) withObject:#"Checking for friends..." waitUntilDone:NO];
NSMutableArray *array = [conCon getAllContactsOnPhone];
// save friends
[processStatusLable performSelectorOnMainThread:#selector(setText:) withObject:#"Saving friends.." waitUntilDone:NO];
if ([dccon saveContacts:array]) {
[processStatusLable performSelectorOnMainThread:#selector(setText:) withObject:#"Friends saved successfully.." waitUntilDone:NO];
}
}
The last performSelector is getting executed (at least I see the label text changed on the view), but all other selectors are not working. Any idea why?
EDIT 1
- (void)updateLabelText:(NSString *)newText {
processStatusLable.text = newText;
}
we can use the following code to run something on the main thread,
dispatch_async(dispatch_get_main_queue(), ^{
//set text label
});
Using that we can write a method like this,
- (void)updateLabelText:(NSString *)newText {
dispatch_async(dispatch_get_main_queue(), ^{
processStatusLable.text = newText;
});
}
Finally, you can use change your code this way,
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self updateLabelText:#"Creating your account..."];
DCConnector *dccon = [DCConnector new];
ContactsConnector *conCon = [ContactsConnector new];
if (![dccon existUsersData]) {
[dccon saveUsersInformation:device :usDTO];
//created account
//get friends -> Server call
[self updateLabelText:#"Checking for friends..."];
NSMutableArray *array = [conCon getAllContactsOnPhone];
// save friends
[self updateLabelText:#"Saving friends.."];
if ([dccon saveContacts:array]) {
[self updateLabelText:#"Friends saved successfully.."];
}
}
});
How fast do you run through this sequence of updates? If it is faster than a second, you aren't likely going to see all of 'em.
Making them wait until done is unlikely to impact anything as the drawing is done asynchronously anyway.
Note that your method names are unconventional; methods shouldn't be prefixed with get and saveUsersInformation:: is discouraged (try something like saveUsersInformationToDevice:usingDTO:).
How much time elapses between the calls to update the text field? The whole process takes a minute, but how is that time divided?
What is your main event loop doing otherwise? Running modally or running normally?

dispatch_async block not getting invoked

MySynchManager class is having a shared instance.
One of the function in MySynchManager class is
- (void)uploadSession:(NSString *)sessionId {
// run the upload process on a separate thread to not to block the main thread for user interaction
// process upload data in serial Queue
NSLog(#"Inside uploadSession");
if (!_serialQueue) {
NSLog(#"uploadSession, _serialQueue is NOT ACTIVE");
[self setRunLoopStarted:FALSE];
_serialQueue = dispatch_queue_create("sessionUploadQueue", NULL);
dispatch_async(_serialQueue, ^{
[[MySyncManager sharedInstance] dispatchSession:sessionId];
});
}
else {
//[self setRunLoopStarted:FALSE];
dispatch_async(_serialQueue, ^{
[self dispatchSession:sessionId];
});
NSLog(#"Adding block to the dispatch queue is complete");
}
}
uploadSession:#"session" is being called from view controllers.
The problem that I am facing is sometimes the code present in dispatchSession is called, but sometimes block is not called.
I only observe the log print statement after the block is printed.
Can any one of you explain the reason behind this?
This is weird code. Try this instead
-(void)uploadSession:(NSString *)sessionId
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_serialQueue = dispatch_queue_create("sessionUploadQueue", NULL);
});
dispatch_async(_serialQueue, ^{
[self dispatchSession:sessionId];
});
}

Dealing with Blocks, completion handlers, dispatch_async vs dispatch_sync

I'm executing an online fetch of data in a thread and I want to do something immediately after the block is executed.
Here's my code:
- (IBAction)refresh:(UIBarButtonItem *)sender {
NSLog(#"checking");
[self editToolbar];
dispatch_queue_t fetchQ = dispatch_queue_create("Refreshing", NULL);
dispatch_async(fetchQ, ^{
[self setupFetchedResultsController];
[self fetchImonggoItemsDataIntoDocument: self.itemDatabase];
});
dispatch_release(fetchQ);
NSLog(#"done checking");
//do something here
}
The thing is dispatch_async returns immediately and "done checking" prints immediately even before the block is done executing. How do I solve this?
I think it's an architectural issue. The tasks are something like:
edit toolbar
fetchImonggoItemsDataIntoDocument
do something else
If these must be done exactly in order then I don't quite understand the use of blocks or queues; just run the statements after each other and you'll be set.
Otherwise, alternative #1 would be to use dispatch_sync rather than dispatch_async. Again, I'm not quite sure what the benefit of using a queue would be but there it is.
Alternative #2 would be to use a callback from the block. Something like:
- (IBAction)refresh:(UIBarButtonItem *)sender {
NSLog(#"checking");
[self editToolbar];
dispatch_queue_t fetchQ = dispatch_queue_create("Refreshing", NULL);
dispatch_async(fetchQ, ^{
[self setupFetchedResultsController];
[self fetchImonggoItemsDataIntoDocument: self.itemDatabase];
[self doneChecking]; // <-- NOTE! call the callback
});
dispatch_release(fetchQ);
}
// NOTE! refresh: has been split up into two methods
- (void)doneChecking:
NSLog(#"done checking");
//do something here
}
As others have already suggested, this is probably what you need.
NSArray *items = [iMonggoFetcher fetchImonggoData:IMONGGO_GENERIC_URL_FOR_PRODUCTS withFormat:#"json" withDateRangeArgs:args];
[document.managedObjectContext performBlock:^{
for (NSDictionary *itemInfo in items){
[Product productWithImonggoInfo:itemInfo inManagedObjectContext:document.managedObjectContext];
}
// Put here what you need :)
}];

Make sure function runs on main thread only

How can I make sure that my function is run only on the main thread? It updates UI elements.
Is a function like this considered 'bad'?
-(void)updateSomethingOnMainThread {
if ( ![[NSThread currentThread] isEqual:[NSThread mainThread]] )
[self performSelectorOnMainThread:_cmd withObject:nil waitUntilDone:NO];
else {
// Do stuff on main thread
}
}
I wrote it like this to avoid having a second function, initially I had it like this:
-(void)updateSomethingOnMainThread_real {
// Do stuff on main thread
}
-(void)updateSomethingOnMainThread {
[self performSelectorOnMainThread:#selector(updateSomethingOnMainThread_real) withObject:nil waitUntilDone:NO];
}
As an alternative to ayoy's method-based GCD implementation for guaranteeing execution on the main thread, I use the following GCD-based function in my code (drawn from another answer of mine):
void runOnMainThreadWithoutDeadlocking(void (^block)(void))
{
if ([NSThread isMainThread])
{
block();
}
else
{
dispatch_sync(dispatch_get_main_queue(), block);
}
}
You can then use this helper function anywhere in your code:
runOnMainThreadWithoutDeadlocking(^{
// Do stuff that needs to be on the main thread
});
This guarantees that the actions taken in the enclosed block will always run on the main thread, no matter which thread calls this. It adds little code and is fairly explicit as to which code needs to be run on the main thread.
This is fine. You can also use GCD to execute code on the main thread.
Checkout this SO post.
GCD to perform task in main thread
I wrote this simple #define which I've been using with great success:
#define ensureInMainThread(); if (!NSThread.isMainThread) { [self performSelectorOnMainThread:_cmd withObject:nil waitUntilDone:NO]; return; }
That way your method, assuming it's parameterless, looks like this
- (void) updateTheThings {
ensureInMainThread();
[self.dog setTailWag:YES];
// etc...
Alternatively, you can use Grand Central Dispatch API, but it's not very handy:
-(void)updateSomethingOnMainThread {
void (^doStuff)(void) = ^{
// stuff to be done
};
// this check avoids possible deadlock resulting from
// calling dispatch_sync() on the same queue as current one
dispatch_queue_t mainQueue = dispatch_get_main_queue();
if (mainQueue == dispatch_get_current_queue()) {
// execute code in place
doStuff();
} else {
// dispatch doStuff() to main queue
dispatch_sync(mainQueue, doStuff);
}
}
otherwise, if synchronous call isn't needed, you can call dispatch_async() which is much simpler:
-(void)updateSomethingOnMainThread {
dispatch_async(dispatch_get_main_queue(), ^{
// do stuff
});
}

GCD, Threads, Program Flow and UI Updating

I'm having a hard time figuring out how to put this all together.
I have a puzzle solving app on the mac.
You enter the puzzle, press a button, and while it's trying to find the number of solutions,
min moves and such I would like to keep the UI updated.
Then once it's finished calculating, re-enable the button and change the title.
Below is some sample code from the button selector, and the solving function:
( Please keep in mind I copy/paste from Xcode so there might be some missing {} or
some other typos.. but it should give you an idea what I'm trying to do.
Basicly, user presses a button, that button is ENABLED=NO, Function called to calculate puzzle. While it's calculating, keep the UI Labels updated with moves/solution data.
Then once it's finished calculating the puzzle, Button is ENABLED=YES;
Called when button is pressed:
- (void) solvePuzzle:(id)sender{
solveButton.enabled = NO;
solveButton.title = #"Working . . . .";
// I've tried using this as a Background thread, but I can't get the code to waitTilDone before continuing and changing the button state.
[self performSelectorInBackground:#selector(createTreeFromNode:) withObject:rootNode];
// I've tried to use GCD but similar issue and can't get UI updated.
//dispatch_queue_t queue = dispatch_queue_create("com.gamesbychris.createTree", 0);
//dispatch_sync(queue, ^{[self createTreeFromNode:rootNode];});
}
// Need to wait here until createTreeFromNode is finished.
solveButton.enabled=YES;
if (numSolutions == 0) {
solveButton.title = #"Not Solvable";
} else {
solveButton.title = #"Solve Puzzle";
}
}
Needs to run in background so UI can be updated:
-(void)createTreeFromNode:(TreeNode *)node
{
// Tried using GCD
dispatch_queue_t main_queue = dispatch_get_main_queue();
...Create Tree Node and find Children Code...
if (!solutionFound){
// Solution not found yet so check other children by recursion.
[self createTreeFromNode:newChild];
} else {
// Solution found.
numSolutions ++;
if (maxMoves < newChild.numberOfMoves) {
maxMoves = newChild.numberOfMoves;
}
if (minMoves < 1 || minMoves > newChild.numberOfMoves) {
solutionNode = newChild;
minMoves = newChild.numberOfMoves;
// Update UI on main Thread
dispatch_async(main_queue, ^{
minMovesLabel.stringValue = [NSString stringWithFormat:#"%d",minMoves];
numSolutionsLabel.stringValue = [NSString stringWithFormat:#"%d",numSolutions];
maxMovesLabel.stringValue = [NSString stringWithFormat:#"%d",maxMoves];
});
}
GCD and performSelectorInBackground samples below. But first, let's look at your code.
You cannot wait where you want to in the code above.
Here's the code you had. Where you say wait in the comment is incorrect. See where I added NO.
- (void) solvePuzzle:(id)sender{
solveButton.enabled = NO;
solveButton.title = #"Working . . . .";
// I've tried using this as a Background thread, but I can't get the code to waitTilDone before continuing and changing the button state.
[self performSelectorInBackground:#selector(createTreeFromNode:) withObject:rootNode];
// NO - do not wait or enable here.
// Need to wait here until createTreeFromNode is finished.
solveButton.enabled=YES;
}
A UI message loop is running on the main thread which keeps the UI running. solvePuzzle is getting called on the main thread so you can't wait - it will block the UI. It also can't set the button back to enabled - the work hasn't been done yet.
It is the worker function's job on the background thread to do the work and then when it's done to then update the UI. But you cannot update the UI from a background thread. If you're not using blocks and using performSelectInBackground, then when you're done, call performSelectorOnMainThread which calls a selector to update your UI.
performSelectorInBackground Sample:
In this snippet, I have a button which invokes the long running work, a status label, and I added a slider to show I can move the slider while the bg work is done.
// on click of button
- (IBAction)doWork:(id)sender
{
[[self feedbackLabel] setText:#"Working ..."];
[[self doWorkButton] setEnabled:NO];
[self performSelectorInBackground:#selector(performLongRunningWork:) withObject:nil];
}
- (void)performLongRunningWork:(id)obj
{
// simulate 5 seconds of work
// I added a slider to the form - I can slide it back and forth during the 5 sec.
sleep(5);
[self performSelectorOnMainThread:#selector(workDone:) withObject:nil waitUntilDone:YES];
}
- (void)workDone:(id)obj
{
[[self feedbackLabel] setText:#"Done ..."];
[[self doWorkButton] setEnabled:YES];
}
GCD Sample:
// on click of button
- (IBAction)doWork:(id)sender
{
[[self feedbackLabel] setText:#"Working ..."];
[[self doWorkButton] setEnabled:NO];
// async queue for bg work
// main queue for updating ui on main thread
dispatch_queue_t queue = dispatch_queue_create("com.sample", 0);
dispatch_queue_t main = dispatch_get_main_queue();
// do the long running work in bg async queue
// within that, call to update UI on main thread.
dispatch_async(queue,
^{
[self performLongRunningWork];
dispatch_async(main, ^{ [self workDone]; });
});
}
- (void)performLongRunningWork
{
// simulate 5 seconds of work
// I added a slider to the form - I can slide it back and forth during the 5 sec.
sleep(5);
}
- (void)workDone
{
[[self feedbackLabel] setText:#"Done ..."];
[[self doWorkButton] setEnabled:YES];
}
dispatch_queue_t backgroundQueue;
backgroundQueue = dispatch_queue_create("com.images.bgqueue", NULL);
- (void)process {
dispatch_async(backgroundQueue, ^(void){
//background task
[self processHtml];
dispatch_async(main, ^{
// UI updates in main queue
[self workDone];
});
});
});
}
By and large, any work to be submitted to a background queue needs to follow this pattern of code:
dispatch_queue_t queue = dispatch_queue_create("com.myappname", 0);
__weak MyClass *weakSelf = self; //must be weak to avoid retain cycle
//Assign async work
dispatch_async(queue,
^{
[weakSelf doWork];
dispatch_async(dispatch_get_main_queue(),
^{
[weakSelf workDone];
});
});
queue = nil; //Using ARC, we nil out. Block always retains the queue.
Never Forget:
1 - queue variable above is a reference counted object, because it is a private queue, not a global one. So it is retained by the block which is executing inside that queue. Until this task is complete, it is not released.
2 - Every queue got its own stack which will be allocated / deallocated as part of recursive operation. You only need to worry about class member variables which are reference counted (strong, retain etc.) which are accessed as part of doWork above.
3 - While accessing those reference counted vars inside background queue operation, you need to make them thread-safe, depending on use cases in your app. Examples include writes to objects such as strings, arrays etc. Those writes should be encapsulated inside #synchronized keyword to ensure thread-safe access.
#synchronized ensures no another thread can get access to the resource it protects, during the time the block it encapsulates gets executed.
#synchronized(myMutableArray)
{
//operation
}
In the above code block, no alterations are allowed to myMutableArray inside the #synchronized block by any other thread.