Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy example of Grand Central Dispatch

I'm newbie programming for mac and i'm really surprised on Grand Central Dispatch. I read about that and looks like the perfect solution for parallel programming. I worked with POSIX threads and want to move to GCD.

I saw the samples codes in the Apple Developer Connection, but It confused me so much. I searched for an easy example with two threads to start but i can't find it.

How can I do this sample code using GCD ???

#include <stdio.h>       /* standard I/O routines                 */
#include <pthread.h>     /* pthread functions and data structures */

/* function to be executed by the new thread */
void* do_loop(void* data)
{
int i;          /* counter, to print numbers */
int j;          /* counter, for delay        */
int me = *((int*)data);     /* thread identifying number */

for (i=0; i<10; i++) 
{
    for (j=0; j<500000; j++) /* delay loop */
    ;
    printf("'%d' - Got '%d'\n", me, i);
}

/* terminate the thread */
pthread_exit(NULL);
}
void* th2(void* data)
{
cout << "Thread nº 2" << endl;
}

int main(int argc, char* argv[])
{
int        thr_id;         /* thread ID for the newly created thread */
pthread_t  p_thread1;
pthread_t  p_thread2;       /* thread's structure                     */
int        a         = 1;  /* thread 1 identifying number            */
int        b         = 2;  /* thread 2 identifying number            */

/* create a new thread that will execute 'do_loop()' */
thr_id = pthread_create(&p_thread1, NULL, do_loop, (void*)&a);
/* run 'do_loop()' in the main thread as well */
thr_id = pthread_create(&p_thread2, NULL, th2, (void*)&b);


return 0;
}

Thanks in advance

like image 392
Jorge Vega Sánchez Avatar asked Mar 31 '11 16:03

Jorge Vega Sánchez


3 Answers

It would be something like this:

// The block replaces your doLoop function, it basically does the same thing
dispatch_block_t myBlock = ^{
    int i;          /* counter, to print numbers */
    int j;          /* counter, for delay        */

    dispatch_queue_t me = dispatch_get_current_queue();     /* The queue which currently runs this block */

    for (i=0; i<10; i++) 
    {
        for (j=0; j<500000; j++) /* delay loop */
            ;


        printf("'%s' - Got '%d'\n", dispatch_queue_get_label(me), i); // Print the name of the queue
    }
};


// Create two queues
dispatch_queue_t queue1 = dispatch_queue_create("my.totally.unique.and.reverse.dns.identifier.1", NULL);
dispatch_queue_t queue2 = dispatch_queue_create("my.totally.unique.and.reverse.dns.identifier.2", NULL);

// Let both execute the block
dispatch_async(queue1, myBlock);
dispatch_async(queue2, myBlock);

// And then release the queues because we are great citizens who care about memory
dispatch_release(queue1);
dispatch_release(queue2);
like image 91
JustSid Avatar answered Nov 20 '22 16:11

JustSid


Just wrap the code that needs to run asynchronously in a block passed to dispatch_async():

int main(int argc, char* argv[])
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
    ^ {
        // This code runs asynchronously!
        for (unsigned long long i = 0ULL; i < 100000000000ULL; i++) {
           cout << i << endl;
        }
    });

    return 0;
}

Note that in both this example and yours, the app will actually return immediately since you do nothing to defer the return from main().

like image 22
Jonathan Grynspan Avatar answered Nov 20 '22 16:11

Jonathan Grynspan


-(void)Search_load_Scraping{

    Reachability *reachability = [Reachability reachabilityForInternetConnection];
    NetworkStatus internetStatus = [reachability currentReachabilityStatus];
    if (internetStatus != NotReachable)
    {



    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
                   ^{

                       TrainInfo  *TrnObj=[[TrainInfo alloc]init];
                       ScrapingClass *scrap=[[ScrapingClass alloc]init];
                       TrnObj=   [scrap train_information: [NSString stringWithFormat:@"http://erail.in/Rail/getPNRStatusAsynch.aspx?Data=%@",pnr_no]];

                       //  NSLog(@"NAME..... %@  NO    %@    Date %@  Class        %@   \ndes==%@\n %@     \n   Dep time %@     Arr time %@   PASSENGER%@      Class       %@", TrnObj.TrainName,TrnObj.TrainNumber,TrnObj.TrainDate,TrnObj.TrainBokingSts,TrnObj.TrainBoarding,TrnObj.TrainDestination,TrnObj.TrainDepTime,TrnObj.TrainArrivalTime,TrnObj.trainTicDictionary,TrnObj.TrainClass);

                       dispatch_sync(dispatch_get_main_queue(), ^{
                           //If self.image is atomic (not declared with nonatomic)
                           // you could have set it directly above
                           [activityIndicator stopAnimating];

                           if ([TrnObj.TrainNumber length]>3){


//**********************                ************************
                               [dbSingleton() createEditableCopyOfDatabaseIfNeeded];
                               if ([dbSingleton()  checkpnrEsistence:pnr_no]>0)
                               {
    //                      [dbSingleton()  deletePnr:pnr_no];
                                   [dbSingleton()  update_Pnr:TrnObj.TrainName trainNumber:TrnObj.TrainNumber chartPrepared:TrnObj.TrainChart className:TrnObj.TrainClass alight_code:TrnObj.TrainDestinationCode alight_name:TrnObj.TrainDestination board_code:TrnObj.TrainBoardingCode board_name:TrnObj.TrainBoarding from_code:TrnObj.TrainDestinationCode from_name:TrnObj.TrainBoarding   tr_date:TrnObj.TrainDate to_code:TrnObj.TrainDestinationCode to_name:TrnObj.TrainDestination BordTime:TrnObj.TrainDepTime FromTime:TrnObj.TrainDepTime ToTime:TrnObj.TrainArrivalTime PNR_number:pnr_no];

                               }

                               [activityIndicator stopAnimating];
                               NSArray *seatdetails=[TrnObj.trainTicDictionary objectForKey:@"passengers"];

            NSLog(@"SCRAPING  self.seat_details %@",self.seat_details);

                               for(int i=0;i<seatdetails.count;i++)
                               {
                                   NSString *seat_number=[NSString stringWithFormat:@"%@",[[seatdetails objectAtIndex:i] objectForKey:@"booking_status"]];
                                   NSString *seat_status=[NSString stringWithFormat:@"%@",[[seatdetails objectAtIndex:i] objectForKey:@"current_status"]];
                                    int roeid=[[[seatdetails objectAtIndex:i] objectForKey:@"rowid"] intValue];

                                   [dbSingleton()  Update_Passenger:seat_number seat_status:seat_status pnr_number:pnr_no Row_ID:roeid];

                               }


//******************************       bord            ************************************
                               NSMutableDictionary *resDicBor=[[NSMutableDictionary alloc]init];
                               [resDicBor setValue:TrnObj.TrainBoardingCode forKey:@"code"];
                               [resDicBor setValue:TrnObj.TrainBoarding forKey:@"name"];
                               [resDicBor setValue:TrnObj.TrainDepTime forKey:@"time"];

                               NSMutableDictionary *resB=[[NSMutableDictionary alloc]init];
                               [resB setValue:resDicBor forKey:@"boarding_point"];
          NSLog(@"SCRAP resB.%@",resB);

//*******************************       des                ********************************
                               NSMutableDictionary *resDicDES=[[NSMutableDictionary alloc]init];
                               [resDicDES setValue:TrnObj.TrainDestinationCode forKey:@"code"];
                               [resDicDES setValue:TrnObj.TrainDestination forKey:@"name"];
                               [resDicDES setValue:TrnObj.TrainArrivalTime forKey:@"time"];

                               NSMutableDictionary *resD=[[NSMutableDictionary alloc]init];
                               [resD setValue:resDicDES forKey:@"reservation_upto"];
         NSLog(@"SCRAP resD.%@",resD);
//*******************************                   *************************************
                               NSMutableDictionary *resDicFro=[[NSMutableDictionary alloc]init];
                               [resDicFro setValue:TrnObj.TrainBoardingCode forKey:@"code"];
                               [resDicFro setValue:TrnObj.TrainBoarding forKey:@"name"];
                               [resDicBor setValue:TrnObj.TrainDepTime forKey:@"time"];

                               NSMutableDictionary *resF=[[NSMutableDictionary alloc]init];
                               [resF setValue:resDicFro forKey:@"from_station"];
        NSLog(@"SCRAP resF.%@",resF);




                               self.travel_details=[[NSMutableArray alloc]init];
                               [self.travel_details addObject:[resD objectForKey:@"reservation_upto"]];
                               [self.travel_details addObject:[resB objectForKey:@"boarding_point"]];
                               [self.travel_details addObject:[resF objectForKey:@"from_station"]];
        NSLog(@"SCRAP from_station....%@",[resF objectForKey:@"from_station"]);
                               self.seat_details=[TrnObj.trainTicDictionary objectForKey:@"passengers"];
        NSLog(@"SCRAP passengers....%@",TrnObj.trainTicDictionary);
                               self.pnr_detail_array=[[NSMutableArray alloc]init];
                               [self.pnr_detail_array addObject:TrnObj.TrainNumber];
        NSLog(@"SCRAP train_number....%@",TrnObj.TrainNumber);

                               NSDateFormatter* Dformatter1 = [[NSDateFormatter alloc] init];
                               [Dformatter1 setDateFormat:@"yyyy-MM-dd"];
                               NSDateFormatter* Dformatter2 = [[NSDateFormatter alloc] init];
                               [Dformatter2 setDateFormat:@"dd-MM-yyyy"];

                               NSDate *TDate=[Dformatter1 dateFromString: TrnObj.TrainDate];
                               NSString *trDat=[Dformatter2 stringFromDate:TDate];
                               [self.pnr_detail_array addObject:trDat];

//        [self.pnr_detail_array addObject:[json objectForKey:@"doj"]];
        NSLog(@"SCRAP date....%@",trDat);
                               [self.pnr_detail_array addObject:TrnObj.TrainName];
                               self.pnr_no=pnr_no;

                               if([TrnObj.TrainChart isEqualToString:@"N"])
                               {
                                   [self.pnr_detail_array addObject:@"Chart Not Prepared"];
                               } else{
                                   [self.pnr_detail_array addObject:@"Chart Prepared"];
                               }
                               [self.pnr_detail_array addObject:@""];
                               [self.pnr_detail_array addObject:TrnObj.TrainClass];

               //*************update seat detail







                               str_seat_detail=@"";
                               for(int i=0;i<seat_details.count;i++)
                               {
                                   str_seat_detail=[str_seat_detail stringByAppendingString:[NSString stringWithFormat:@"%@-%@\n",[[seat_details objectAtIndex:i] objectForKey:@"booking_status"],[[seat_details objectAtIndex:i] objectForKey:@"current_status"]]];
                               }

              NSLog(@" SCRAP  str_seat_detail  %@",str_seat_detail);
                               [table_view reloadData];

                           }else{

                            if (delegateObj.ScrapStatus==1) {

                            [self performSelector:@selector(getLoginData) withObject:nil afterDelay:0.0];
                                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"Trying Again"
                                                                                   delegate:self  cancelButtonTitle:nil
                                                                          otherButtonTitles:nil];
                                [alertView show];
                                [self performSelector:@selector(byeAlertView:) withObject:alertView afterDelay:0.5];
                            }else{
                               [activityIndicator stopAnimating];
                               UIAlertView *alert =[[UIAlertView alloc]initWithTitle:nil message:@"Either the PNR is not generated or the travel date is in the past." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                               [alert show];
                               }
                           }

                       });
                   });

    }else
    {
        [activityIndicator stopAnimating];
        UIAlertView *alert =[[UIAlertView alloc]initWithTitle:@"Oops!" message:@" Try again later." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }

}
like image 42
mahendra Avatar answered Nov 20 '22 17:11

mahendra