开发者

Boost threading/mutexs, why does this work?

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) {
//b开发者_如何学运维oost::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;
}

Output:

0
2
4
6
8
10
12
14
16
18
Press any key to continue . . .

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

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.


It works because of the thds.join_all(); line. The main execution thread traps here until all the other threads are completed, then continues to print out the array. Therefore you know that all the array values have been stored before you print them. If you comment out this line you will get unpredictable results.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜