gpt4 book ai didi

ios - iOS 中的操作同步挑战

转载 作者:搜寻专家 更新时间:2023-10-31 23:03:01 25 4
gpt4 key购买 nike

我有 3 个操作:ABC

  • A,B可以并发处理
  • 如果 C 运行,AB 应该等待
  • 如果 AB 运行 C 应该等待

我会用一个调度组和一个信号量来解决它:

public var dgLoadMain = dispatch_group_create()
public var semaLoadMain = dispatch_semaphore_create(1)

A, B 看起来像这样:

dispatch_group_enter(dgLoadMain)
dispatch_semaphore_wait(semaLoadMain, DISPATCH_TIME_FOREVER)
dispatch_semaphore_signal(semaLoadMain) //maybe odd, but right after wait, it signals, it just check wether C is in critical section, if not, release semaphore, and let other B or A continue too
//..
dispatch_group_leave(dgLoadMain)

C 看起来像这样:

dispatch_group_wait(dgLoadMain, DISPATCH_TIME_FOREVER)
dispatch_semaphore_wait(semaLoadMain, DISPATCH_TIME_FOREVER)
//..
dispatch_semaphore_signal(semaLoadMain)

你觉得可以吗?

最佳答案

dispatch_barrier_async 更复杂。看看这段代码。它是 Objective-C,但同样的概念绝对适用于 Swift。

#import <Foundation/Foundation.h>

void A()
{
NSLog(@"A begin");
sleep(1);
NSLog(@"A end");
}

void B()
{
NSLog(@"B begin");
sleep(1);
NSLog(@"B end");
}

void C()
{
NSLog(@"C begin");
sleep(1);
NSLog(@"C end");
}

int main()
{
dispatch_queue_t q = dispatch_queue_create("ABC", DISPATCH_QUEUE_CONCURRENT);

dispatch_queue_t qA = dispatch_queue_create("A", DISPATCH_QUEUE_SERIAL);
dispatch_set_target_queue(qA, q);

dispatch_queue_t qB = dispatch_queue_create("B", DISPATCH_QUEUE_SERIAL);
dispatch_set_target_queue(qB, q);

dispatch_barrier_async(q, ^{C();});
dispatch_async(qA, ^{A();});
dispatch_async(qA, ^{A();});
dispatch_async(qB, ^{B();});
dispatch_barrier_async(q, ^{C();});
dispatch_async(qB, ^{B();});
dispatch_barrier_async(q, ^{C();});
dispatch_async(qA, ^{A();});

dispatch_main();
return 0;
}

结果。

C begin
C end
A begin
B begin
A end
B end
B begin
A begin
B end
A end
A begin
A end
C begin
C end
C begin
C end

关于ios - iOS 中的操作同步挑战,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31180876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com