It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center。
6年前关闭。
为什么以下代码具有竞争条件?
__sync_add_and_fetch()函数将第二个参数添加到第一个参数并返回总和。所有这些都是原子操作。这比抓取和释放锁更有效率
6年前关闭。
为什么以下代码具有竞争条件?
static int i=0;
void some_fun()
{
++i;
if(2==i)
{
printf("some message");
}
}
最佳答案
假设这是从多个线程调用的,则需要保护静态变量i。
可以使用前面提到的锁来完成,或者在这种情况下使用更有效的原子递增操作。
如果您使用的是gcc编译器,则它将如下所示:
static int i=0;
void some_fun()
{
int local_i = __sync_add_and_fetch(&i, 1);
if(2==local_i)
{
printf("some message");
}
}
__sync_add_and_fetch()函数将第二个参数添加到第一个参数并返回总和。所有这些都是原子操作。这比抓取和释放锁更有效率
关于c - 为什么以下代码中的竞争条件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15378352/