typeidx: use atomic variables for thread safety

This commit is contained in:
Danny Robson 2018-04-05 12:14:11 +10:00
parent cd06fdcd67
commit 190307acb8
2 changed files with 6 additions and 5 deletions

View File

@ -16,11 +16,12 @@
#include "typeidx.hpp" #include "typeidx.hpp"
#include <atomic>
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
std::uintptr_t int
util::detail::typeidx_next () util::detail::typeidx_next ()
{ {
static std::uintptr_t counter = 0; static std::atomic<int> counter = 0;
return counter++; return counter++;
} }

View File

@ -20,7 +20,7 @@
#include <cstdint> #include <cstdint>
namespace util { namespace util {
namespace detail { std::uintptr_t typeidx_next (void); } namespace detail { int typeidx_next (void); }
/// return a globally unique runtime ID for a given type. /// return a globally unique runtime ID for a given type.
/// ///
@ -29,13 +29,13 @@ namespace util {
/// ///
/// the identifier is constructed at runtime and is not guaranteed to be /// the identifier is constructed at runtime and is not guaranteed to be
/// stable across executions (particularly in the case of threads and /// stable across executions (particularly in the case of threads and
/// other non-determinism). /// other non-determinism). however it _is_ threadsafe to call this.
/// ///
/// the range of identifiers is _probably_ contiguous starting from zero. /// the range of identifiers is _probably_ contiguous starting from zero.
/// this should not be relied upon for correctness, but may be used for /// this should not be relied upon for correctness, but may be used for
/// performance concerns. /// performance concerns.
template <typename T> template <typename T>
std::uintptr_t int
typeidx (void) typeidx (void)
{ {
static auto id = detail::typeidx_next (); static auto id = detail::typeidx_next ();