繁体   English   中英

提升线程/互斥量,为什么这样做?

[英]Boost threading/mutexs, why does this work?

码:

#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次),产生上述输出,即使锁定被注释掉了? 我认为一般的想法是:

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寄存器吗? 或者,在将结果写回ram之前,它是否会被计算得过于抢占? 谢谢。

赋值在左边有一个double类型的左值,而lvalue是一个线程访问的唯一对象。 由于每个线程访问不同的对象,因此没有数据争用。

请注意,下载数组不构成访问。

它的工作原因是thds.join_all(); 线。 主执行线程陷阱,直到所有其他线程完成,然后继续打印出阵列。 因此,您知道在打印之前已存储了所有数组值。 如果你注释掉这一行,你将得到不可预知的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM