【发布时间】:2013-10-08 10:23:05
【问题描述】:
我在 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();
}
- 注释第 24、26 和 32 行需要 9 秒才能完成。
- 只有第 24、26 行注释和 32 未注释,完成也需要 9 秒。
- 没有注释的行需要 18 秒才能完成
我认为这两个线程是独立的,a.foo() 行是否有锁并不重要。但确实如此,为什么呢?
【问题讨论】:
标签: c++ multithreading mutex boost-thread boost-mutex