gpt4 book ai didi

c - 原子整数增量

转载 作者:行者123 更新时间:2023-11-30 17:42:31 26 4
gpt4 key购买 nike

让我们有一个函数来递增全局原子整数,然后将该值存储在非原子局部变量中

_Atomic int atom = 0 ;

void function( void )
{
int a = atom++ ;
}

在多线程中使用上述代码时,a 是否始终具有唯一值。如果像一些评论者所建议的那样,那么像 atomic_fetch_add 这样的函数有什么意义呢? .

最佳答案

我不熟悉“_Atomic”关键字。这是 C++11 的新东西吗?无论如何,您应该使用大多数平台和 CPU 架构中内置的原子内在函数。 (x86 中的“lock add”)。

在 GCC/Clang 上,想要调用的函数是 __sync_add_and_fetch 。在 Windows 上,它称为 InterlockedIncrement .

在某些仍以 i386 为目标的 gcc 架构上,您必须在汇编中手动执行此操作。 (虽然这在真正的 80386 上不起作用,直到 80486 才引入锁内在函数,但我离题了......)

unsigned int xadd_4(volatile void* pVal, unsigned int inc)
{
unsigned int result;
unsigned int* pValInt = (unsigned int*)pVal;

asm volatile(
"lock; xaddl %%eax, %2;"
:"=a" (result)
: "a" (inc), "m" (*pValInt)
:"memory" );

return (result);
}

int AtomicIncrement(int* pInt)
{
COMPILE_TIME_ASSERT(sizeof(int)==4);
// InterlockedIncrement
unsigned int result = xadd_4(pInt, 1) + 1;
return (int)result;
}

关于c - 原子整数增量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20526346/

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