mutex and threads independence

半世苍凉 提交于 2019-12-24 11:44:39

问题


I run the following program on a 32 cores 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();
}
  1. With lines 24, 26 and 32 commented it takes 9 seconds to complete.
  2. With only lines 24, 26 commented and 32 uncommented it takes also 9 seconds to complete.
  3. With no lines commented it takes 18 seconds to complete

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


回答1:


A mutex means that only one thread at a time can enter a piece of code. So that means that the first thread to line 24 will block the second thread until the first thread reaches line 26.

In other words, the mutex does make one thread dependent on the other when they both try to acquire the mutex.




回答2:


Yes the two threads are independent but the mutex they are using is same. So if that mutex is locked, then the thread will get stuck till mutex is released by the other thread.



来源:https://stackoverflow.com/questions/19130074/mutex-and-threads-independence

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!