views:

59

answers:

2

Hi, when I try to run the following code in debug and release mode in VS2005. Each time I see different output in console and It doesn't seem like the multithreading is achieved in release mode.

1. #include <boost/thread.hpp> 
2. #include <iostream> 
3.
4. void wait(int seconds) 
5. { 
6.   boost::this_thread::sleep(boost::posix_time::seconds(seconds)); 
7. } 
8. 
9. boost::mutex mutex; 
10. 
11. void thread() 
12. { 
13.  for (int i = 0; i < 5; ++i) 
14.  { 
15.    //wait(1);
16.    mutex.lock(); 
17.    std::cout << "Thread " << boost::this_thread::get_id() << ": " << i << std::endl; 
18.    mutex.unlock(); 
19.  } 
20. } 
21.
22. int main() 
23. { 
24.   boost::thread t1(thread); 
25.   boost::thread t2(thread); 
26.   t1.join(); 
27.   t2.join(); 
28. }

Debug Mode

Thread 00153E60: 0
Thread 00153E90: 0
Thread 00153E60: 1
Thread 00153E90: 1
Thread 00153E90: 2
Thread 00153E60: 2
Thread 00153E90: 3
Thread 00153E60: 3
Thread 00153E60: 4
Thread 00153E90: 4
Press any key to continue . . .

Release Mode

Thread 00153D28: 0
Thread 00153D28: 1
Thread 00153D28: 2
Thread 00153D28: 3
Thread 00153D28: 4
Thread 00153D58: 0
Thread 00153D58: 1
Thread 00153D58: 2
Thread 00153D58: 3
Thread 00153D58: 4
Press any key to continue . . .
+1  A: 

Both scenarios are correct. In release mode t1 is already finished before t2 is started. The difference between debug and release is pure accidental. Because release runs faster you get different timing.

Eddy Pronk
+1  A: 

If you uncomment the call to wait(), it is evident that both threads are running at the same time. Likewise, if you increase the number of times the loop is run to 1,000, you can see the threads are interleaved (well, 1,000 on my computer; it might take more or less).

Remember that a release build is optimized, so tasks almost always take less time and threads may end up scheduled differently in a release build than in a debug build.

James McNellis