std::thread::id
和std::this_thread::get_id()
的线程安全比较operator==如下所示?
std::thread::id t_id;
许多线程中的某个地方:
if(t_id != std::this_thread::get_id()) {
while(lock.test_and_set(std::memory_order_acquire));
++recursive_counter ;
t_id = std::this_thread::get_id();
// ...
if (--recursive_counter == 0)
t_id = std::thread::id();
lock.clear(std::memory_order_release);
}
例如,Boost 1.62用于比较线程id:
pthread_equal(owner,pthread_self())
:http://www.boost.org/doc/libs/1_62_0/boost/thread/pthread/recursive_mutex.hpp
::boost::detail::interlocked_read_acquire(&locking_thread_id)==current_thread_id
:http://www.boost.org/doc/libs/1_62_0/boost/thread/win32/basic_recursive_mutex.hpp
已知pthread_equal()
是线程安全的,interlocked_read_acquire()
是线程安全的。
但是如何在C ++ 11/14中比较两个std::thread::id
而不是std::mutex
?
我可以在下面使用吗?
std::atomic<std::thread::id> t_id;
许多线程中的某个地方:
if(t_id.load(std::memory_order_acquire) != std::this_thread::get_id()) {
while(lock.test_and_set(std::memory_order_acquire));
++recursive_counter;
t_id.store(std::this_thread::get_id(), std::memory_order_release);
// ...
if (--recursive_counter == 0)
t_id.store(std::thread::id(), std::memory_order_release);
lock.clear(std::memory_order_release);
}
std::atomic<std::thread::id> t_id;
的结果:
两者的结果:
t_id.is_lock_free() = true
sizeof(t_id) = 8
结果:
t_id.is_lock_free() = true
sizeof(t_id) = 8
结果:
t_id.is_lock_free() = true
sizeof(t_id) = 4
is_lock_free() = true
是否意味着,(t_id.load(std::memory_order_acquire) != std::this_thread::get_id())
是线程安全的,并且不使用std::mutex
?