首页 > 编程语言 > 详细

c++ 随机数 取值范围 多线程

时间:2020-08-05 09:51:16      阅读:102      评论:0      收藏:0      [点我收藏+]

 

#include <random>  

std::random_device rd;                         // A function object for generating seeds
  std::mt19937 gen(rd());
  std::uniform_int_distribution<> dis(1, 6000);//取值 1-6000

使用:
 dis(gen)

线程延迟随机多少秒内启动:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include <thread>
#include <random>

using namespace std;
using std::cout;

class HelloWorld {
public:
    HelloWorld(string url)
    {
        std::random_device rd;                         // A function object for generating seeds
        std::mt19937 gen(rd());
        std::uniform_int_distribution<> dis(1, 6000);//

        const int len = 100;
        std::thread threads[len];
        std::cout << "Spawning 5 threads...\n";
        for (int i = 0; i < len; i++) {
            threads[i] = std::thread(&HelloWorld::thread_task, this, url, dis(gen));
        }

        std::cout << "Done spawning threads! Now wait for them to join\n";
        for (auto& t : threads) {
            t.join();
        }
        std::cout << "All threads joined.\n";
    }

    void thread_task(string url, int time) {
        std::this_thread::sleep_for(std::chrono::milliseconds(time));
        std::cout << "hello thread "
            << std::this_thread::get_id()
            << " paused " << time << " milliseconds" << std::endl;
    }
};

int main() {
 
    HelloWorld hw("url");

    return EXIT_SUCCESS;
}

 

c++ 随机数 取值范围 多线程

原文:https://www.cnblogs.com/bigben0123/p/13437838.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!