0

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

#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;
}
4

1 回答 1

0

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

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

于 2013-06-12T02:51:25.483 回答