0

Is this the correct way to sync threads without mutex. This code should be running for a long time

#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;
}
yohjp
  • 2,985
  • 3
  • 30
  • 100

1 Answers1

0

Without knowing exactly what you're trying to do, it is hard to say it is the "correct" way. That's valid code, it's a bit janky though.

There is no guarantee that the "Checker" thread will ever see the condition y > x. It's theoretically possible that it will never break. In practice, it will trigger at some point but x might not be LONG_MIN and y LONG_MAX. In other words, it's not guaranteed to trigger just as the overflow happens.

Guillaume
  • 2,044
  • 12
  • 11