![](/img/trans.png)
[英]Why boost::geometry::intersection does not work correct?
[英]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.