Easy example of Grand Central Dispatch

后端 未结 3 2025
深忆病人
深忆病人 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:26

    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().

提交回复
热议问题