【问题标题】:C++ Are pseudo random number generators thread safe?C++ 伪随机数生成器线程安全吗?
【发布时间】:2015-12-06 08:18:03
【问题描述】:

Q1:伪随机数生成器线程安全吗?我可以在多个线程中使用共享生成器吗?

#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关键字,它仍然为不同的线程生成不同的整数序列,那么lock有什么用?

【问题讨论】:

  • @James Root 不,该帖子写道:“就像容器需要锁才能安全共享一样,您必须锁定 PRNG 对象。”但我没有使用锁,它可以工作也很好。我想知道有什么区别。

标签: c++ multithreading random


【解决方案1】:

如果您不需要每个线程的确定性序列,可以使用带有一个 PRNG 的锁。如果伪随机序列在不同运行中的不同线程上不能有所不同,那么每个线程使用一个 PRNG。

【讨论】:

  • 不,我使用了共享生成器,没有锁,在thread_local关键字上,它为每个线程返回不同的整数序列。
  • 因为从两个 PRNG 生成的序列不一定提供与使用一个相同的保证(确实不太可能)。不过,还有其他解决方案可以为多个线程生成随机数而无需锁定。
  • @Voo 我只使用了一个 PRNG,声明为 :random_device 种子; default_random_engine 引擎(seed());
  • @iouvxy "为每个线程返回不同的整数序列" - 这就是 deterministic 的含义。正如我所说。
  • @Paul Evans 我很困惑,对不起我的英语不好。我只想为每个线程提供随机整数,看来我已经实现了我的目标。但是在另一篇文章中,有人写道“就像容器需要锁才能安全共享一样,您必须锁定 PRNG 对象。”我没有,但我的代码看起来不错,那么锁有什么用,我可以只需使用一个共享生成器。
猜你喜欢
  • 1970-01-01
  • 2012-02-07
  • 1970-01-01
  • 2020-01-31
  • 2012-08-19
  • 2015-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多