首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >gcc装配中的atomic_inc和atomic_xchg

gcc装配中的atomic_inc和atomic_xchg
EN

Stack Overflow用户
提问于 2013-01-13 07:50:44
回答 1查看 4.3K关注 0票数 0

我编写了以下用户级代码片段来测试两个子函数:原子incxchg (参见Linux代码)。我需要的只是尝试对32位整数执行操作,这就是我显式使用int32_t的原因。我认为global_counter将被不同的线程所竞争,而tmp_counter则很好。

代码语言:javascript
复制
#include <stdio.h>
#include <stdint.h>
int32_t global_counter = 10;

/* Increment the value pointed by ptr */
void atomic_inc(int32_t *ptr)
{
    __asm__("incl %0;\n"
        : "+m"(*ptr));
}

/* 
 * Atomically exchange the val with *ptr.
 * Return the value previously stored in *ptr before the exchange
 */
int32_t atomic_xchg(uint32_t *ptr, uint32_t val)
{
    uint32_t tmp = val;
    __asm__(
        "xchgl %0, %1;\n"
        : "=r"(tmp), "+m"(*ptr)
        : "0"(tmp)
        :"memory");
    return tmp;
}

int main()
{
    int32_t tmp_counter = 0;

    printf("Init global=%d, tmp=%d\n", global_counter, tmp_counter);

    atomic_inc(&tmp_counter);
    atomic_inc(&global_counter);
    printf("After inc, global=%d, tmp=%d\n", global_counter, tmp_counter);

    tmp_counter = atomic_xchg(&global_counter, tmp_counter);
    printf("After xchg, global=%d, tmp=%d\n", global_counter, tmp_counter);

    return 0;
}

我的两个问题是:

  1. 这两个子函数写得是否正确?
  2. 当我在32位或64位平台上编译这个程序时,这种情况会是一样的吗?例如,指针地址是否具有不同的长度。或者inclxchgl是否会与操作数发生冲突?
EN

回答 1

Stack Overflow用户

发布于 2013-01-14 02:06:11

我对这个问题的理解如下,如果我错了,请纠正我。

所有的读-修改-写指令(例如:包括,添加,xchg)都需要一个锁前缀.锁指令是通过在存储器总线上断言LOCK#信号来锁定其他CPU访问的内存。

Linux内核中的__xchg函数不包含“锁”前缀,因为xchg始终意味着锁定。64.h#L15

但是,atomic_inc中使用的incl没有这个假设,因此需要一个lock_prefix。http://lxr.linux.no/linux+v2.6.38/arch/x86/include/asm/atomic.h#L105

顺便说一下,我认为您需要将*ptr复制到易失性变量,以避免gcc优化。

威廉

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14301644

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档