Multithreading

Can anyone tell what is going on here? When I try to debug the code and when the control is in the thread () function on line 15, it skips line 16, moving to line 17, and returns line 16. Why not move line by line?

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. } 
+4
source share
2 answers

Perhaps your debugger actually runs multiple threads in parallel, so it seems to jump back and forth. Try printing the thread id from your debugger and you will probably see different numbers at each stop.

Another reason for the weird transition to debugging is if the code is optimized. If so, the source code order does not require compiled code matching

+5
source

What does your conclusion look like when it jumps? It looks like this could be a problem with multiple threads.

0
source

Source: https://habr.com/ru/post/1309689/


All Articles