Simply use:
std::atomic<int> id{};
int create_id() {
return id++;
}
See http://en.cppreference.com/w/cpp/atomic/atomic/operator_arith
Related Contents:
- c++, std::atomic, what is std::memory_order and how to use them?
- What exactly is std::atomic?
- Can num++ be atomic for ‘int num’?
- When to use volatile with multi threading?
- When do I really need to use atomic instead of bool? [duplicate]
- Understanding std::atomic::compare_exchange_weak() in C++11
- Where is the lock for a std::atomic?
- Must I call atomic load/store explicitly?
- What does the [[carries_dependency]] attribute mean?
- How to implement multithread safe singleton in C++11 without using
- difference between standard’s atomic bool and atomic flag
- Why don’t compilers merge redundant std::atomic writes?
- Are C/C++ fundamental types atomic?
- Does std::atomic work appropriately?
- Are atomic variables lock-free?
- How to atomically negate an std::atomic_bool?
- Double-Checked Lock Singleton in C++11
- Is incrementing an int effectively atomic in specific cases?
- Acquire/Release versus Sequentially Consistent memory order
- Do I have to use atomic for “exit” bool variable?
- Start thread with member function
- Thread pooling in C++11
- What happens to a detached thread when main() exits?
- How do I terminate a thread in C++11?
- Example for boost shared_mutex (multiple reads/one write)?
- Does the C++ volatile keyword introduce a memory fence?
- When to use recursive mutex?
- Pass multiple arguments into std::thread
- How can I distinguish between high- and low-performance cores/threads in C++?
- How do “acquire” and “consume” memory orders differ, and when is “consume” preferable?
- What happens when an exception goes unhandled in a multithreaded C++11 program?
- Multithreading and multicore differences
- What operations are atomic in C#?
- Waiting for multiple futures?
- What’s the best way to lock multiple std::mutex’es?
- Can I use std::async without waiting for the future limitation?
- What are the “things to know” when diving into multi-threaded programming in C++
- How to easily make std::cout thread-safe?
- Using stdlib’s rand() from multiple threads
- Is it safe to read an integer variable that’s being concurrently modified without locking?
- Is it ok to read a shared boolean flag without locking it when another thread may set it (at most once)?
- What is lock-free multithreaded programming?
- What does the C++ compiler do to ensure that different but adjacent memory locations are safe to be used on different threads?
- What is the best way to wait on multiple condition variables in C++11?
- Use std::lock_guard with try_lock
- atomic increment and return counter
- Is std::lock() ill-defined, unimplementable, or useless?
- How to give priority to privileged thread in mutex locking?
- What is the difference between std::condition_variable::wait_for and std::condition_variable::wait_until?
- Difference between pointer and reference as thread parameter