可能重複:
ID generator with local static variable - thread-safe?功能局部靜態變量唯一ID生成
請問下面的函數每次調用時返回一個唯一的號碼?在多線程場景中怎麼樣?
int returnUniqueNumber()
{
static int i = 0;
++i;
return i;
}
可能重複:
ID generator with local static variable - thread-safe?功能局部靜態變量唯一ID生成
請問下面的函數每次調用時返回一個唯一的號碼?在多線程場景中怎麼樣?
int returnUniqueNumber()
{
static int i = 0;
++i;
return i;
}
這取決於你的平臺,否則你會遇到多線程問題。在窗戶上,您最好關閉以下設備:
int returnUniqueNumber()
{
volatile static long l = 0;
return (int)InterlockedIncrement(&l);
}
Interlocked*功能是保證原子的。
從戈茲貝達的有關窗口答案繼,對於Linux/GCC看到這個提問/回答:
Equivalent of InterlockedIncrement in Linux/gcc
在這種情況下,你會想__sync_add_and_fetch()
如果您的應用程序是單線程,您發佈的代碼實際上是正確的,符合標準的C/C++生成唯一編號的方式。但是,由於您正在尋找一個線程安全的解決方案,因此您必須深入瞭解特定於平臺的解決方案。 Goz有一個很好的Windows解決方案。在Mac OS X或iOS的等效是:
int returnUniqueNumber_APPLE(void) {
static volatile int32_t i = 0;
return (int)OSAtomicIncrement32Barrier(&i);
}
你在哪裏有最近十歲上下的GCC編譯任何系統,你也有GCC的內部函數:
int returnUniqueNumber_GCC(void) {
static volatile int i = 0;
return __sync_add_and_fetch(&i, 1);
}
看起來我們已經涵蓋了Windows,Linux和MacOS :) – 2010-11-21 13:21:30
不僅僅是Linux,而是大多數* NIXes。 :)事實上,我們已經涵蓋了幾乎所有主要的現代系統。 Android可能是唯一的一個,你可以在函數的返回類型之前拋出一個'synchronized'關鍵字並完成。 (Java是否有適當的原子操作?我不是指'AtomicInteger'等) – 2010-11-21 13:23:02
你不應該投的'靜int *'轉換爲'volatile long *'--rather,在兩種情況下它都應該是一個(合適的)合法的'LONG *',並且在返回時(或者只是由函數隱式地)強制轉換爲int。 '和'int'(和Windows的'LONG' typedef)並不總是相同的大小,雖然這種轉換可能在Windows上很好,但它鼓勵壞習慣。 :) – 2010-11-21 13:11:05
@喬納森:採取點,固定。 – Goz 2010-11-21 13:12:43
我向你致敬,先生。 +1和簡單準確的代碼+1! – 2010-11-21 13:13:48