Possible Duplicate:
ID generator with local st开发者_JAVA百科atic variable - thread-safe?
Would the following function return a unique number every time it is called? What about in a multi-threaded scenario?
int returnUniqueNumber()
{
static int i = 0;
++i;
return i;
}
It depends on your platform as to ehwther you'll get multithreading issues. On windows you'd be best off doing the following:
int returnUniqueNumber()
{
volatile static long l = 0;
return (int)InterlockedIncrement( &l );
}
The Interlocked* functions are guaranteed atomic.
If your application were single-threaded, the code you posted would be in fact the correct, standards-compliant C/C++ way of generating unique numbers. However, since you're looking for a thread-safe solution, you must dive into platform-specific solutions. Goz has a good Windows solution. An equivalent on Mac OS X or iOS would be:
int returnUniqueNumber_APPLE(void) {
static volatile int32_t i = 0;
return (int)OSAtomicIncrement32Barrier(&i);
}
On any system where you compile with a recent-ish GCC, you also have GCC's intrinsics:
int returnUniqueNumber_GCC(void) {
static volatile int i = 0;
return __sync_add_and_fetch(&i, 1);
}
Following on from Goz's answer regarding windows, for Linux/GCC see this question/answer:
Equivalent of InterlockedIncrement in Linux/gcc
in which case you'll want __sync_add_and_fetch()
精彩评论