3

所以我期待下面的程序打印两行。但是它不打印任何东西。关于需要修复什么的任何想法?

#import <Foundation/Foundation.h>
#import <dispatch/dispatch.h>

int main(int argc, char **argv)
{
 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
 printf("Done outer async\n");
    dispatch_async(dispatch_get_main_queue(),^{
         printf("Done inner sync");
    });
 });

 return 0;
}

谢谢

4

2 回答 2

6

dispatch_main()如果您的程序没有事件循环,则必须调用:

int main(int argc, char **argv)
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
        printf("Done outer async\n");
        dispatch_async(dispatch_get_main_queue(),^{
            printf("Done inner sync");
        });
    });

    dispatch_main();
    return 0;
}

从文档中:

此函数“停放”主线程并等待将块提交到主队列。调用UIApplicationMain (iOS)、NSApplicationMain(Mac OS X) 或CFRunLoopRun在主线程上的应用程序不得调用dispatch_main.

于 2013-08-31T15:45:42.690 回答
2

您的主线程首先结束,当您返回 0 时关闭其余线程——这就是为什么没有打印任何内容,因为您的其他调度没有机会被执行。

于 2013-08-31T15:44:01.810 回答