atomic_inc_return() 是否保证原子 return 值?
Does atomic_inc_return() guarantee atomic return value?
想象一下以下用例:
static atomic_t ref_counter = ATOMIC_INIT(0);
void incref(void) {
if (atomic_inc_return(&ref_counter) == 1) {
// init my stuff
}
}
void decref(void) {
if (atomic_dec_return(&ref_counter) == 0) {
// release my stuff
}
}
如果两个线程同时调用incref()
,ref_counter
在两次调用后保证有值2
。
但是原子执行是否也应用于 return 值?我的意思是,我们是否保证其中一个线程会 return 1
而第二个线程 return 会 2
?或者他们都可以 return 1
?
But does the atomic execution get applied to the return value too?
这就是这些功能的全部意义所在,否则它们就没有多大意义。 atomic_*_return
的全部要点是变量的修改和获取值的发生 原子地 。
I mean, are we guaranteed that one of the threads will return 1 while the second one returns 2?
是的。原子访问彼此顺序。
Or they both may return 1?
没有
想象一下以下用例:
static atomic_t ref_counter = ATOMIC_INIT(0);
void incref(void) {
if (atomic_inc_return(&ref_counter) == 1) {
// init my stuff
}
}
void decref(void) {
if (atomic_dec_return(&ref_counter) == 0) {
// release my stuff
}
}
如果两个线程同时调用incref()
,ref_counter
在两次调用后保证有值2
。
但是原子执行是否也应用于 return 值?我的意思是,我们是否保证其中一个线程会 return 1
而第二个线程 return 会 2
?或者他们都可以 return 1
?
But does the atomic execution get applied to the return value too?
这就是这些功能的全部意义所在,否则它们就没有多大意义。 atomic_*_return
的全部要点是变量的修改和获取值的发生 原子地 。
I mean, are we guaranteed that one of the threads will return 1 while the second one returns 2?
是的。原子访问彼此顺序。
Or they both may return 1?
没有