0

pthreads を使用するプログラムがあります。各スレッドでは、rand() (stdlib.h) 関数を使用して乱数が生成されます。しかし、すべてのスレッドが同じ乱数を生成しているようです。その理由は何ですか??..私は何か間違ったことをしていますか??..ありがとう

4

1 に答える 1

1

rand()疑似ランダムであり、シード する必要があるかどうかに関係なく、スレッドセーフであることが保証されていませんrand()

std::srand(std::time(0)); // use current time as seed for random generator

詳細についてstd::rand()は、cppreference.comを参照してください。

サンプルプログラムは次のようになります。

#include <cstdlib>
#include <iostream>
#include <boost/thread.hpp>

boost::mutex output_mutex;

void print_n_randoms(unsigned thread_id, unsigned n)
{
    while (n--)
    {
        boost::mutex::scoped_lock lock(output_mutex);
        std::cout << "Thread " << thread_id << ": " << std::rand() << std::endl;
    }
}

int main()
{
    std::srand(std::time(0));
    boost::thread_group threads;
    for (unsigned thread_id = 1; thread_id <= 10; ++thread_id)
    {
        threads.create_thread(boost::bind(print_n_randoms, thread_id, 100));
    }
    threads.join_all();
}

疑似乱数ジェネレーターに時間が1回だけ(スレッドごとではなく)シードされることに注意してください。

于 2013-02-01T04:36:33.803 に答える