【发布时间】:2011-02-28 02:26:25
【问题描述】:
代码:
#include <iostream>
#include "stdafx.h"
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
using namespace std;
boost::mutex mut;
double results[10];
void doubler(int x) {
//boost::mutex::scoped_lock lck(mut);
results[x] = x*2;
}
int _tmain(int argc, _TCHAR* argv[])
{
boost::thread_group thds;
for (int x = 10; x>0; x--) {
boost::thread *Thread = new boost::thread(&doubler, x);
thds.add_thread(Thread);
}
thds.join_all();
for (int x = 0; x<10; x++) {
cout << results[x] << endl;
}
return 0;
}
输出:
0 2 4 6 8 10 12 14 16 18 按任意键继续 。 . .
所以...我的问题是为什么这个工作(据我所知,我运行了大约 20 次)产生上述输出,即使锁定已被注释掉? 我认为总体思路是:
在每个线程中: 计算 2*x 将结果复制到 CPU 寄存器 将计算存储在数组的正确部分 将结果复制回主(共享)内存我认为在几乎完美的条件下,这将导致结果数组的某些部分具有 0 值。它只是将数组所需的双精度复制到 cpu 寄存器吗?还是在将结果写回内存之前,计算量太少而无法被抢占?谢谢。
【问题讨论】:
标签: c++ multithreading boost mutex