是两个std :: thread :: id的线程安全比较运算符吗?

时间:2016-10-28 14:40:40

标签: c++ multithreading c++11 boost concurrency

std::thread::idstd::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()是线程安全的,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
  • Windows MSVS2013(v120):

结果:

t_id.is_lock_free() = true
sizeof(t_id) = 8
  • Windows MSVS2013(v120):

结果:

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

0 个答案:

没有答案