views:

92

answers:

1

I don't see synchronized output when i comment the the line wait(1) in thread(). can I make them run at the same time (one after another) without having to use 'wait(1)'?

#include <boost/thread.hpp> 
#include <iostream> 

void wait(int seconds) 
{
  boost::this_thread::sleep(boost::posix_time::seconds(seconds)); 
}

boost::mutex mutex; 

void thread()
{
  for (int i = 0; i < 100; ++i) 
  {
    wait(1); 
    mutex.lock(); 
    std::cout << "Thread " << boost::this_thread::get_id() << ": " << i << std::endl; 
    mutex.unlock(); 
  }
}

int main()
{
  boost::thread t1(thread); 
  boost::thread t2(thread);

  t1.join();
  t2.join();
}
+2  A: 

"at the same time (one after another)" is contradictory. With a call to sleep() they run at the same time. Without a call to sleep(), they run one after another. With only 100 lines to output, thread t1 completes before t2 has a change to begin execution. On my computer, I had to set your loop counter to 10000 before t1 ran long enough for t2 to launch while t1 was still executing:

Thread 0x2305010: 0
Thread 0x2305010: 1
Thread 0x2305010: 2
...
Thread 0x2305010: 8730
Thread 0x2305010: 8731
Thread 0x23052a0: 0
Thread 0x23052a0: 1
...
Thread 0x23052a0: 146
Thread 0x23052a0: 147
Thread 0x2305010: 8732
Thread 0x2305010: 8733
etc

Oh, and yes, if your goal was to make the two threads take turns executing, boost::condition_variable is the solution:

boost::mutex mutex;
boost::condition_variable cv;

void thread()
{
  for (int i = 0; i < 100; ++i)
  {
    boost::unique_lock<boost::mutex> lock(mutex);
    std::cout << "Thread " << boost::this_thread::get_id() << ": " << i << std::endl;
    cv.notify_one();
    cv.wait(lock);
  }
  cv.notify_one();
}
Cubbi