Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

scott455

macrumors member
Original poster
Jun 5, 2022
40
0
I am new to objective C in macos. Is there an example using GCD and runloop?.
 
Last edited:

chown33

Moderator
Staff member
Aug 9, 2009
10,990
8,874
A sea of green
I added [CODE] [/CODE] tags around your code blocks. I tried to correct some of the smiley icons, but I may have missed some. You might want to check the revised code and see if it's still correct.
 

Senor Cuete

macrumors 6502
Nov 9, 2011
429
31
Threads are obsolete. Apple advises you to move away from them in favor of Grand Central Dispatch - a robust way to run tasks concurrently:


Apple silicon processors get their high performance from parallelism - not higher clock speeds (although these chips will clock faster and be more efficient). The next generation of M processors will have a LOT of cores. GCD gives you a way to take advantage of this without trying to figure out how many cores are available, etc. GCD does this all for you in a very optimized way.

For a long time this was only available in Objective C but recently it has been added to swift as well.
 

scott455

macrumors member
Original poster
Jun 5, 2022
40
0
I have read several articles and examples in GCD, RUNLOOP but still could not apply it to the above code. I'll keep trying , in meanwhile, Is there any good examples for doing what the above code does?.
 

mfram

Contributor
Jan 23, 2010
1,353
396
San Diego, CA USA
Here is an example of using GCD to do your prints. Each little block that prints one line is done independently. So it won't be in numerical order necessarily. In order to wait for all of them to complete, you create a dispatch group and wait for all of the blocks in the group to complete.

Code:
//
//  main.m
//  DispatchPrint
//

#import <Foundation/Foundation.h>

static void print_line(int i)
{
    printf("%2d\n", i);
}

void dispatch_prints(void)
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);
    dispatch_group_t group = dispatch_group_create();

    for(int i = 0; i< 100; i++)
    {
        dispatch_group_async(group, queue, ^{print_line(i);});
    }

    dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
}

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        dispatch_prints();
    }

    return 0;
}
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.