简体   繁体   English

C:如何使此函数具有线程安全性?

[英]C: How to make this function thread-safe?

Usually when I want to make functions thread-safe I lock the shared data, then release when I'm finished doing work. 通常,当我想使函数成为线程安全的时,我会锁定共享数据,然后在完成工作后释放。

Here I'm working with a global variable. 在这里,我正在使用全局变量。 Simply locking and unlocking is not going to ensure that the function returns a unique value. 简单地锁定和解锁并不能确保该函数返回唯一值。 How do I modify the following function to be thread-safe and ensure it always returns a unique integer? 如何将以下函数修改为线程安全的,并确保其始终返回唯一的整数?

int count = 0;
int GetUnique()
  {
    count = count + 1;
    return count;
  }

Some people have mentioned making a local static variable inside the function? 有人提到在函数内部创建局部静态变量? How and why would this work (if true)? 这将如何以及为何起作用(如果为真)?

You want to in this case use an atomic increment, no need for locking or mutexes if you use GCC intrinsics. 在这种情况下,您希望使用原子增量,如果您使用GCC内部函数,则无需锁定或互斥。 __sync_add_and_fetch is what you are looking for here, or for VC InterlockedIncrement will perform the same. __sync_add_and_fetch是您在此处寻找的内容,否则对于VC InterlockedIncrement将会执行相同的操作。

You could make this code portable with the following: 您可以使用以下代码使此代码可移植:

#ifdef _WIN32
#define SYNC_ADD_AND_FETCH(x) InterlockedIncrement(&(x))
#else
#define SYNC_ADD_AND_FETCH(x) __sync_add_and_fetch(&(x), 1)
#endif

int main(int argc, char *argv[])
{
  int v = 0;
  SYNC_ADD_AND_FETCH(v);
  printf("%d\n", v);
}

Making it static is not enough to protect the variable from other threads modifying it on the fly, in fact it does not help in any way. 将其设置为静态还不足以保护该变量不受其他线程即时修改的影响,实际上,它无济于事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM