Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/135.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 互斥和线程独立性_C++_Multithreading_Mutex_Boost Thread_Boost Mutex - Fatal编程技术网

C++ 互斥和线程独立性

C++ 互斥和线程独立性,c++,multithreading,mutex,boost-thread,boost-mutex,C++,Multithreading,Mutex,Boost Thread,Boost Mutex,我在32核计算机上运行以下程序: #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; +

我在32核计算机上运行以下程序:

#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();
}
#包括
#包括
#包括
使用名称空间std;
boost::线程组g;
boost::mutex\u mtx;
甲级{
公众:
void foo()
{   
对于(int-ix=0;ix<10000000;++ix)
向量推回(ix);
排序(vec.rbegin(),vec.rend());
}   
私人:
向量向量机;
};
void thread_fun()
{
A A;
_mtx.lock();//第24行
a、 foo();
_mtx.unlock();//第26行
}
int main()
{
g、 添加线程(新的boost::thread(thread_-fun));
g、 添加线程(新的boost::thread(thread\u fun));//第32行
g、 加入所有人;
}
  • 对第24行、第26行和第32行进行注释需要9秒才能完成
  • 只有第24行、第26行注释行和第32行未注释行,完成此操作也需要9秒
  • 如果没有行注释,则需要18秒才能完成

  • 我认为这两个线程是独立的,在
    a.foo()
    行上是否有锁并不重要。但是,为什么呢?

    互斥体意味着一次只能有一个线程输入一段代码。这意味着第24行的第一个线程将阻塞第二个线程,直到第一个线程到达第26行


    换句话说,当两个线程都试图获取互斥时,互斥确实会使一个线程依赖于另一个线程。

    是的,两个线程是独立的,但它们使用的互斥是相同的。因此,如果该互斥锁被锁定,那么该线程将被卡住,直到另一个线程释放互斥锁为止