C++ 使用线程生成唯一随机数

C++ 使用线程生成唯一随机数,c++,random,pthreads,C++,Random,Pthreads,我有一个使用pthreads的程序。在每个线程中,使用rand()函数(stdlib.h)生成一个随机数。但似乎每个线程都在生成相同的随机数。原因是什么??。。我做错什么了吗??。。感谢rand()是且不保证线程安全的,不管怎样,您需要为rand()设定种子: 有关更多详细信息,请参阅 示例程序可能如下所示: #include <cstdlib> #include <iostream> #include <boost/thread.hpp> boost::m

我有一个使用pthreads的程序。在每个线程中,使用rand()函数(stdlib.h)生成一个随机数。但似乎每个线程都在生成相同的随机数。原因是什么??。。我做错什么了吗??。。感谢

rand()
是且不保证线程安全的,不管怎样,您需要为
rand()
设定种子:

有关更多详细信息,请参阅

示例程序可能如下所示:

#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();
}
#包括
#包括
#包括
boost::互斥输出\互斥;
无效打印\u n\u随机数(未签名的线程\u id,未签名的n)
{
而(n--)
{
boost::mutex::作用域锁定(output\u mutex);

std::cout一个随机种子只是一个用来初始化伪随机数生成器的数字。@Zeus就像你从不同的种子中得到不同形式和种类的植物一样,你从不同的随机生成器种子中得到不同的数字集。@MarkGarcia谢谢。这是一个很好的例子。你很好地清除了它。许多C标准函数都不是幸运的是,RAND还有一个线程安全的版本-<代码> RANDYR 。请参见详细信息。在VisualC++中,有代码> RANDYS 。@乐高:这是一个有用的点,特别是如果需要重复的伪随机数生成测试(和代码< RANDYR)()
适用于所有目标系统)!
#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();
}