【问题标题】:Is this the correct way to thread sync with out mutex这是使用互斥锁进行线程同步的正确方法吗
【发布时间】:2013-06-07 23:33:54
【问题描述】:

这是在没有互斥锁的情况下同步线程的正确方法吗? 这段代码应该会运行很长时间

#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/memory_order.hpp>
#include <atomic>

std::atomic<long> x =0;
std::atomic<long> y =0;

boost::mutex m1;

// Thread increments
void Thread_Func()
{
    for(;;)
    {
//      boost::mutex::scoped_lock lx(m1);
        ++x;
        ++y;
    }
}

// Checker Thread
void Thread_Func_X()
{
    for(;;)
    {
//      boost::mutex::scoped_lock lx(m1);
        if(y > x)
        {
// should never hit until int overflows
            std::cout << y << "\\" << x << std::endl;
            break;
        }
    }
}

//Test Application
int main(int argc, char* argv[])
{
    boost::thread_group threads;
    threads.create_thread(Thread_Func);
    threads.create_thread(Thread_Func_X);
    threads.join_all();
    return 0;
}

【问题讨论】:

    标签: memory atomic lock-free barrier


    【解决方案1】:

    在不确切知道您要做什么的情况下,很难说这是“正确”的方式。这是有效的代码,但它有点笨拙。

    不能保证“检查器”线程会看到条件y &gt; x。从理论上讲,它可能永远不会破裂。在实践中,它会在某个时候触发,但 x 可能不是 LONG_MIN 和 y LONG_MAX。换句话说,它不能保证在溢出发生时触发。

    【讨论】:

      猜你喜欢
      • 2014-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-30
      • 2016-06-21
      • 1970-01-01
      • 2016-07-08
      相关资源
      最近更新 更多