gpt4 book ai didi

objective-c - OSAtomicIncrement32 锁定什么?

转载 作者:行者123 更新时间:2023-12-03 12:52:00 30 4
gpt4 key购买 nike

OSAtomicIncrement32 锁定什么? Dispatch_async 是否会导致原子调用对于原始变量来说不是线程安全的?

static volatile int32_t count;
...
dispatch_async(dispatch_get_main_queue(), ^{
...
OSAtomicIncrement32(&count);
}

volatile 是否多余,或者即使计数始终以原子方式递增,某些线程也可能读取旧值?

编辑:http://www.drdobbs.com/parallel/volatile-vs-volatile/212701484 解决了这个不稳定的问题。 。这可以通过以下答案中的几个链接找到,但我想我会将其发布在这里以供快速引用。简而言之,“ volatile ”在 Java 中与 Objective-C 中的含义不同。

最佳答案

来自Apple documentation :

Nonblocking synchronization is a way to perform some types of operations and avoid the expense of locks. Although locks are an effective way to synchronize two threads, acquiring a lock is a relatively expensive operation, even in the uncontested case. By contrast, many atomic operations take a fraction of the time to complete and can be just as effective as a lock.

Atomic operations let you perform simple mathematical and logical operations on 32-bit or 64-bit values. These operations rely on special hardware instructions (and an optional memory barrier) to ensure that the given operation completes before the affected memory is accessed again. In the multithreaded case, you should always use the atomic operations that incorporate a memory barrier to ensure that the memory is synchronized correctly between threads.

因此,您应该使用OSAtomicIncrement32Barrier来确保线程之间共享的内存正确同步。根据this answer ,只有当参数不用于访问任何其他数据时,才应该使用非屏障函数

查看this question的答案关于原子操作中 volatile 关键字的使用。

关于objective-c - OSAtomicIncrement32 锁定什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35900911/

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