我编写了以下用户级代码片段来测试两个子函数:原子inc和xchg (参见Linux代码)。我需要的只是尝试对32位整数执行操作,这就是我显式使用int32_t的原因。我认为global_counter将被不同的线程所竞争,而tmp_counter则很好。
#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;
}我的两个问题是:
incl和xchgl是否会与操作数发生冲突?发布于 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优化。
威廉
https://stackoverflow.com/questions/14301644
复制相似问题