簡體   English   中英

C ++偽隨機數生成器線程安全嗎?

[英]C++ Are pseudo random number generators thread safe?

問題1:偽隨機數生成器線程安全嗎? 我可以在多個線程中使用共享生成器嗎?

#include "stdafx.h"
#include <iostream>
#include <thread>
#include <random>
#include <math.h>  
using namespace std;
random_device seed;//Should I use thread_local here?
default_random_engine engine(seed());//Should I use thread_local here?
int random_int(int x, int y)
{
    binomial_distribution<int> distribution(y - x);
    return distribution(engine) + x;
}
int a[10],b[10],c[10];
void thread_task() {
    for (int i = 0; i < 10; i++)
    {
        a[i] = random_int(1, 8);
    }
}
void thread_task1() {
    for (int i = 0; i < 10; i++)
    {
        b[i] = random_int(1, 8);
    }
}
void thread_task2() {
    for (int i = 0; i < 10; i++)
    {
        c[i] = random_int(1, 8);
    }
}
int main()
{
    thread t(thread_task);
    thread t1(thread_task1);
    thread t2(thread_task2);
    t.join();
    t1.join();
    t2.join();
    for (int i = 0; i < 10; i++)
        cout << a[i] << " ";
    cout << endl;
    for (int i = 0; i < 10; i++)
        cout << b[i] << " ";
    cout << endl;
    for (int i = 0; i < 10; i++)
        cout << c[i] << " ";
    cout << endl;
    getchar();
    return 0;
}

result 1:
7 4 4 3 7 5 4 4 4 4
5 4 4 7 2 3 6 5 4 7
4 4 4 6 1 6 3 5 3 4 //seems fine.
result 2:
5 3 5 6 3 4 5 5 3 5
5 6 5 6 8 3 5 7 3 2
4 6 4 5 4 4 4 3 6 7 //still works fine.

Q2:線程安全是否意味着無鎖?

如果一個類是線程安全的,那是否意味着我可以在不鎖定它的情況下在多個線程中使用它的共享實例?

Q3:我既沒有使用lock也不使用thread_local關鍵字,它仍然為不同的線程生成不同的整數序列,那么鎖有什么用呢?

如果不需要每個線程的確定性序列,可以使用帶有一個PRNG的使用鎖。 如果偽隨機序列在不同運行期間的不同線程之間不能不同,則對每個線程使用PRNG。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM