如何在调度块中使用std::atomic<bool>?

问题描述 投票:0回答:1

以下代码中存在 Call toimplicitly-deleted copy constructor of 'std::atomic' 错误,std::mutex 也是同样的情况。
我只能使用串行队列来进行同步?

__block std::atomic<bool> balance(false); // Call to implicitly-deleted copy constructor of 'std::atomic<bool>' error
dispatch_block_t work = dispatch_block_create(static_cast<dispatch_block_flags_t>(0), ^{
    if (!balance) {
        long l = dispatch_semaphore_signal(semaphore);
        NSLog(@"task 2 %d", l);
        balance = true;
    }
});

你能帮我一下吗?非常感谢!

objective-c macos grand-central-dispatch atomic
1个回答
0
投票

__block
变量最终被复制:https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Blocks/Articles/bxVariables.html#//apple_ref/doc/uid/TP40007502- CH6-SW1

(我认为这个操作理论上可以使用移动构造函数,如果可用的话?但它没有,所以我们在这里。)

最简单的解决方案可能是使用

shared_ptr
。较低开销的选项是可能的,但
shared_ptr
的优点是易于使用并为您提供适当的对象生命周期管理。例如,对于此处给出的代码:

__block auto balance = std::make_shared<std::atomic<bool>>(false);
dispatch_block_t work = dispatch_block_create(static_cast<dispatch_block_flags_t>(0), ^{
    if (!*balance) {
        long l = dispatch_semaphore_signal(semaphore);
        NSLog(@"task 2 %d", l);
        *balance = true;
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.