I am trying to learn how to use atomic :)
class foo {
static std::atomic<uint32_t> count_;
uint32 increase_and_get() {
uint32 t = count_++;
return t;
}
}
Is the function increase_and_get()
thread-safe?
Yes, it is safe: the increment is atomic, and the local t
cannot be altered by concurrent threads. You can further simplify your code to eliminate the temporary variable altogether:
uint32 increase_and_get() {
return count_++;
}
Yes, it would be threadsafe. Assuming of course there are no bugs in the std::atomic
implementation - but it's not usually hard to get right.
This is exactly what std::atomic
is meant to do.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.