Easy example of Grand Central Dispatch

后端 未结 3 2014
深忆病人
深忆病人 2021-02-02 01:59

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 wit

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-02 02:08

    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);
    

提交回复
热议问题