开发者

Unique ID with ::InterlockedIncrement (VC++)

Using VC++, to get a unique ID that counts upwards, I was wondering whether this is legal in a multi-threaded application?

uint32_t GetNewId() { return ::InterlockedIncrement(&lastId); }

Basically, I am wondering whether InterlockedIncrement just protects the increment, or whether the return value i开发者_运维问答s also guarded against race conditions?


Yes, that is legal - the access which consists of

  • read, then
  • increment, then
  • write, then
  • return the incremented value to the caller

will be atomic. Just don't forget that it's 32 bit and can overflow.


Function results are returned in registers and/or stack. Each thread has a separate stack and register set so, yes, this is safe. The InterlockedIncrement will do what it does an its returned value is then no different to any other function result - your function can be interruted and reentered from another thread and will return the correct result for both.

Rgds, Martin


The best way to check is to go to the source.

This function is atomic with respect to calls to other interlocked functions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜