Improve thread sync in release
when i try to run the following code in debug and release mode in VS2005. Every time I see a different output in the console and it doesn't seem like 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 . . .
+2
a source to share
2 answers
If you uncomment the call wait()
, it is obvious that both threads are running at the same time. Likewise, if you increase the number of loops during which the loop is 1000, you can see that the threads are interleaved (well, 1000 on my computer, it may take more or less).
Remember that the release build is optimized, so tasks almost always take less time, and threads can be scheduled differently in release builds than in debug builds.
+1
a source to share