我开发了一个基于 gcc 原子内置函数的可重入函数。不幸的是,我收到有关“已计算但未使用”值的神秘警告:
$ gcc -c -Wall ss.c
ss.c: In function ‘ss_wrapper’:
ss.c:87:3: warning: value computed is not used [-Wunused-value]
__atomic_exchange_n(&ss_top, hit, __ATOMIC_SEQ_CST);
^
ss.c:91:5: warning: value computed is not used [-Wunused-value]
__atomic_exchange_n(&ss_top, bkp->next, __ATOMIC_SEQ_CST); // release the lock, find out if there is new element
^
这是我的功能:
static void ss_wrapper(int signum, siginfo_t* siginfo, void *ucontext) {
// currently top element on the signal stack
static struct ss_hit* ss_top = NULL;
struct ss_hit* hit = ss_newhit(signum, siginfo, (ucontext_t*)ucontext);
struct ss_hit* bkp;
again:
bkp = hit;
__atomic_exchange_n(&ss_top, hit, __ATOMIC_SEQ_CST);
if (!hit) { // we got the lock, we are the master
ss_fire(bkp);
// release the lock, find out if there is new element
__atomic_exchange_n(&ss_top, bkp->next, __ATOMIC_SEQ_CST);
if (bkp->next) { // there IS
hit = bkp;
free(bkp);
goto again;
} else
free(bkp);
} else { // we didn't got the lock, but we got the top in hit
__atomic_store(&hit->next, &bkp, __ATOMIC_SEQ_CST);
}
}
为什么会发生这种情况? __atomic_exchange_n
不应计算任何内容,它仅交换两个变量的内容。
最佳答案
it only swaps the content of two variables
不,事实并非如此。它将一个变量的内容与寄存器的内容交换。第二个变量永远不会改变。 (即使没有查阅文档,这从传递两个参数的不同约定中可以明显看出——原子交换的内存地址作为指针传递,另一个值被复制,而不是就地访问)
由于这种误解,你的逻辑就被打破了。你的意思是:
hit = __atomic_exchange_n(&ss_top, hit, __ATOMIC_SEQ_CST);
if (!hit) { // we got the lock, we are the master
它将寄存器的新值写回第二个变量。对 hit
的访问是非原子的,但这没关系,因为它是一个局部变量,不与任何其他线程共享。
不要直接扔掉返回值,如果这样做,你将永远无法进入“我们是主人”的分支
关于c - __atomic_exchange_n 上的神秘 "value computed is not used"警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32423671/