2012-01-12 39 views
0

我想用C++ 11多線程化我的部分代碼。在std :: array中存儲rng的列表以實現多線程

我創建這樣一羣RNG年代:

typedef std::mt19937 mersenne_twister; 
typedef std::uniform_real_distribution<double> unidist; 

// 8 rng engines with 8 consecutive seeds 
const size_t Nrng = 8; 
const array<uint32_t,Nrng> seed_values = {0,1,2,3,4,5,6,7}; 
array<mersenne_twister,Nrng> engines; 
const array<unidist,Nrng> distributions; // default constructor is for [0,1] interval 

const array<????,Nrng> rngs; // What type do I put here? 

for(size_t i=0; i<Nrng; ++i) 
    engines[i].seed(seed_values[i]); 
    rngs[i] = std::bind(distributions[i], engines[i]); 

的想法,我可以每個RNG對象的使用提供的生成後傳遞給一個單獨的std::thread,填補另一array某種形式的隨機數。我不知道我需要使用什麼類型的rng array。我知道如何創建一個RNG,像這樣:

auto rng = std::bind(unidist, generator); 

,但我需要明確地有鍵入arraydecltype d?)。

+2

你真的需要存儲分佈嗎?他們只是一些沒有狀態的小型來電適配器。你可能只需要一個* global *'unidist',並在需要的地方使用'unidist(rngs [i])'。 – 2012-01-12 12:15:28

回答

2

一種可能的類型是std::function<double()>,但請注意,這不是免費的。 bind的結果的實際類型是不可知的,因此您不能僅製作一個元素類型爲decltype(std::bind(...))的容器,因爲這些類型不能保證是可以相互轉換的 - 您只需要知道它們全部轉換爲function

如果這對性能至關重要,我建議您將目標代碼中的配置文件std::function與直接使用unidist(rngs[i])進行比較。 (這個發行版是一個無狀態的適配器,無論如何都應該是可重入的,所以你不需要保留多個副本。)

+0

感謝您的有用答案。我將創建一個全局的'unidist'變量,並將'mersenne_twister'傳遞給我的函數,通過調用'unidist(引擎)'產生隨機數。 – rubenvb 2012-01-12 13:42:37