升压线程/ mutexs,为什么这项工作? [英] Boost threading/mutexs, why does this work?

查看:94
本文介绍了升压线程/ mutexs,为什么这项工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

code:

#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
Press any key to continue . . .

所以...我的问题是,为什么做这项工作(据我所知道的,我跑了约20倍),产生上面的输出,即使锁定注释掉?
我认为总体思路是:

So...my question is why does this work(as far as i can tell, i ran it about 20 times), producing the above output, even with the locking commented out? I thought the general idea was:


in each thread:
calculate 2*x
copy results to CPU register(s)
store calculation in correct part of array
copy results back to main(shared) memory

我认为所有,但完善的条件下,这将导致其0值的结果数组的某些部分。难道只是复制数组CPU寄存器的双重要求?或者只是太短计算写入结果之前回公羊得到preempted?谢谢你。

I would think that under all but perfect conditions this would result in some part of the results array having 0 values. Is it only copying the required double of the array to a cpu register? Or is it just too short of a calculation to get preempted before it writes the result back to ram? Thanks.

推荐答案

在分配类型的左值双击左侧和左值正在访问的唯一对象由一个线程。因为每个线程访问一个不同的对象,不存在数据的种族。

The assignment has an lvalue of type double on the left and that lvalue is the only object being accessed by a thread. Since each thread accesses a different object, there is no data race.

注意,下标数组并不构成访问。

Note that subscripting an array does not constitute an access.

这篇关于升压线程/ mutexs,为什么这项工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆