我编写了以下用户级代码片段来测试两个子函数,原子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;
}
我的两个问题是:
- 这两个子函数写得正确吗?
- 当我在 32 位或 64 位平台上编译它时,它的行为是否相同?例如,指针地址是否可以具有不同的长度。或者可能
incl
并且xchgl
将与操作数冲突?