Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

下列代码运行没有效果 #18

Open
XiMuYouZi opened this issue Apr 21, 2018 · 0 comments
Open

下列代码运行没有效果 #18

XiMuYouZi opened this issue Apr 21, 2018 · 0 comments

Comments

@XiMuYouZi
Copy link

  • (void)viewDidLoad {
    [super viewDidLoad];
    //因为用到了dispatch_barrier_async,该函数只能搭配自定义并行队列dispatch_queue_t使用。所以不能使用:dispatch_get_global_queue
    dispatch_queue_t queue = dispatch_queue_create("com.ioschengxuyuan.gcd.ForBarrier", DISPATCH_QUEUE_CONCURRENT);
    /*
    *
    *生成Dispatch Semaphore
    Dispatch Semaphore 的计数初始值设定为“1”
    (该初始值的1与下文中两个函数dispatch_semaphore_wait与dispatch_semaphore_signal进行的减1、加1里的1没有必然联系。

    就算初始值是100,两个函数dispatch_semaphore_wait与dispatch_semaphore_signal还是会减“1”、加“1”)。
    保证可访问 NSMutableArray 类对象的线程
    同时只能有1个
    *
    */
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(1) ;
    NSMutableArray array = [[NSMutableArray alloc] init];
    for(int i = 0; i< 100000; ++i) {
    dispatch_async(queue, ^{
    /

    *
    *等待Dispatch Semaphore
    *一直等待,直到Dispatch Semaphore的计数值达到大于等于1
    /
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) ;
    /

    *由于Dispatch Semaphore的计数值达到大于等于1
    *所以将Dispatch Semaphore的计数值减去1
    *dispatch_semaphore_wait 函数执行返回。
    *即执行到此时的
    *Dispatch Semaphore 的计数值恒为0
    *
    *由于可访问NSMutaleArray类对象的线程
    *只有一个
    *因此可安全地进行更新
    *
    /
    NSLog(@"🔴%@",[NSThread currentThread]);
    [array addObject:[NSNumber numberWithInt:i]];
    /

    *
    *排他控制处理结束,
    *所以通过dispatch_semaphore_signal函数
    *将Dispatch Semaphore的计数值加1
    *如果有通过dispatch_semaphore_wait函数
    *等待Dispatch Semaphore的计数值增加的线程,
    ★就由最先等待的线程执行。
    /
    dispatch_semaphore_signal(semaphore);
    });
    }
    /

    *
    等为数组遍历添加元素后,检查下数组的成员个数是否正确
    *
    */
    dispatch_barrier_async(queue, ^{
    NSLog(@"🔴类名与方法名:%s(在第%d行),描述:%@", PRETTY_FUNCTION, LINE, @([array count]));
    });
    }

上面是文中的代码,实际运行后发现,不会运行dispatch_barrier_async方法里面的代码,做如下更改才可以:

把原文中的代码:
for(int i = 0; i< 100000; ++i) {
dispatch_async(queue, ^{
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) ;

改成:
for(int i = 0; i< 100000; ++i) {
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) ;
dispatch_async(queue, ^{

才可以,楼主验证下看是不是这样

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant