C++随机uniform_int_distribution在所有线程中返回相同的值
C++ random uniform_int_distribution return same values in all threads
我有以下代码,我需要在给定的时间间隔内有一个随机数。似乎按照我需要的方式工作。
std::default_random_engine eng;
std::uniform_int_distribution<int> dist(3, 7);
int timeout = dist(eng);
但是后来我在不同的线程中运行它并在循环中重复。
std::default_random_engine defRandEng(std::this_thread::get_id());
std::uniform_int_distribution<int> dist(3, 7);
int timeout; // if I put timeout = dist(defRandEng); here it's all the same
while (true)
{
timeout = dist(defRandEng);
std::cout<<"Thread "<<std::this_thread::get_id()<<" timeout = "<<timeout<<std::endl;
std::this_thread::sleep_for(std::chrono::seconds(timeout));
}
但是对于所有线程中的每次迭代,值都是相同的
Thread 139779167999744 timeout = 6
Thread 139779134428928 timeout = 6
Thread 139779067287296 timeout = 6
Thread 139779117643520 timeout = 6
Thread 139779100858112 timeout = 6
Thread 139779084072704 timeout = 6
Thread 139779151214336 timeout = 6
Thread 139779050501888 timeout = 6
Thread 139779033716480 timeout = 6
下一页
Thread 139779167999744 timeout = 4
Thread 139779151214336 timeout = 4
Thread 139779134428928 timeout = 4
Thread 139779117643520 timeout = 4
Thread 139779100858112 timeout = 4
Thread 139779084072704 timeout = 4
Thread 139779067287296 timeout = 4
Thread 139779050501888 timeout = 4
Thread 139779033716480 timeout = 4
您需要根据随机引擎的一些自然随机值提供种子。以下示例采用自您的代码片段,适用于 3 个线程:
std::mutex lock;
void sample_time_out()
{
std::stringstream ss;
ss << std::this_thread::get_id();
uint64_t thread_id = std::stoull(ss.str());
std::default_random_engine eng(thread_id);
std::uniform_int_distribution<int> dis(3, 7);
for (int i = 0; i < 3; i++)
{
auto timeout = dis(eng);
std::this_thread::sleep_for(std::chrono::seconds(timeout));
{
std::unique_lock<std::mutex> lock1(lock);
std::cout << "Thread " << std::this_thread::get_id() << " timeout = " << timeout << std::endl;
}
}
}
int main()
{
std::thread t1(sample_time_out);
std::thread t2(sample_time_out);
std::thread t3(sample_time_out);
t1.join();
t2.join();
t3.join();
return 0;
}
我第一次运行的输出是:
Thread 31420 timeout = 3
Thread 18616 timeout = 6
Thread 31556 timeout = 7
Thread 31420 timeout = 4
Thread 18616 timeout = 7
Thread 31420 timeout = 6
Thread 31556 timeout = 7
Thread 18616 timeout = 4
Thread 31556 timeout = 7
相关文章:
- CoInitialize()在单独的线程上崩溃而不返回
- 将数组作为多线程应用程序中函数的返回传递
- 为什么 pthread_create() 返回 0 但线程从未启动
- 在多线程函数中返回共享的常量指针会导致计时问题吗?
- C++ 线程端回调并返回结果
- 当加入 C++11 函数的线程仍未终止时,是否可以返回?
- SetWindowsHookEx 在挂接到其他线程时返回 NULL
- 单一实例对象是否通过线程安全返回shared_ptr
- 为什么这些静态函数没有按预期从另一个线程返回?
- 取消来自辅助线程的请求以强制MPI_Wait返回
- 如何在另一个线程中关闭 MFC 模式对话框并获取对话框返回值?
- 有没有办法为任何函数编写通用代码,以便它可以(异步)执行并从线程池中获得返回值?
- C++线程中调用 std::terminate 时程序返回代码
- 如何在 c++ 中从线程开始(返回)
- 如何在 CUDA 中的块中返回其他线程
- 返回可中断线程的函数
- C++ 线程函数指针实现返回错误无效使用非静态成员函数
- 只有在上一个线程返回后才启动一个新的"wxThread"
- C++ cv::Mat 返回向量的<rectangle>线程异步
- 如何从升压线程获得返回值