Mutex and thread independence

I run the following program on a 32-core computer:

#include<iostream> #include<algorithm> #include<boost/thread.hpp> using namespace std; boost::thread_group g; boost::mutex _mtx; class A{ public: void foo() { for(int ix = 0; ix < 10000000; ++ix) vec.push_back(ix); sort(vec.rbegin(), vec.rend()); } private: vector<int> vec; }; void thread_fun() { A a; _mtx.lock(); //line 24 a.foo(); _mtx.unlock(); //line 26 } int main() { g.add_thread(new boost::thread(thread_fun)); g.add_thread(new boost::thread(thread_fun)); //line 32 g.join_all(); } 
  • Reading lines 24, 26, and 32 takes 9 seconds.
  • If only lines 24, 26 are commented out and 32 are uncommented, it takes another 9 seconds.
  • No comment comments takes 18 seconds to complete

I thought the two threads are independent, and it doesn't matter if there is a lock on the a.foo() or not. But it is so, why?

+1
c ++ multithreading mutex boost-mutex boost-thread
source share
2 answers

Mutex means that only one thread at a time can enter a piece of code. Thus, this means that the first thread to line 24 will block the second thread until the first thread reaches line 26.

In other words, a mutex makes one thread dependent on the other when they are both trying to get a mutex.

+1
source share

Yes, the two threads are independent, but the mutex they use is the same. Therefore, if this mutex is blocked, then the thread will become stuck until the mutex is released by another thread.

+1
source share

All Articles