设为首页 加入收藏

TOP

C++11新特性(五)
2016-04-27 17:25:22 】 浏览:928
Tags:特性
lock & lock, const std::chrono::time_point & timeout_time, Predicate pred);
#include 
   
     // std::cout #include 
    
      // std::thread #include 
     
       // std::mutex, std::unique_lock #include 
      
        // std::condition_variable std::mutex mtx; std::condition_variable cv; bool ready = false; void print_id (int id) { std::unique_lock
       
         lck(mtx); // 下面两句话是一样的 // while (!ready) cv.wait(lck); cv.wait(lck, []{return ready;}); std::cout << "thread " << id << '\n'; } void go() { std::unique_lock
        
          lck(mtx); ready = true; cv.notify_all(); } void condition_variable_usage() { std::thread threads[10]; // spawn 10 threads: for (int i=0; i<10; ++i) { threads[i] = std::thread(print_id, i); } std::cout << "10 threads ready to race...\n"; go(); for (auto& th : threads) { th.join(); } }
        
       
      
     
    
   

atomic

原子类型对象的主要特点就是从不同线程访问不会导致数据竞争(data race)。因此从不同线程访问某个原子对象是良性 (well-defined) 行为,而通常对于非原子类型而言,并发访问某个对象(如果不做任何同步操作)会导致未定义 (undifined) 行为发生。

#include 
   
     int main() { std::atomic
    
      ai(5); ai++; ai += 100; return 0; }
    
   

随机数


标准把随机数抽象成随机数引擎和分布两部分.引擎用来产生随机数,分布产生特定分布的随机数(比如平均分布,正太分布等)

标准提供三种常用的引擎:

linear_congruential_engine mersenne_twister_engine subtract_with_carry_engine。

第一种是线性同余算法,第二种是梅森旋转算法,第三种带进位的线性同余算法。第一种是最常用的,而且速度也是非常快的.

随机数引擎接受一个整形参数当作种子,不提供的话,会使用默认值,推荐使用random_device来产生一个随机数当作种子

#include 
   
     #include 
    
      int main() { { // random_device是一个随机数设备,不同的操作
     系统有不同的实现,linux下是读取/dev/urandom设备 std::random_device rd; for (int i = 0; i < 10; i++) { std::cout << rd() << std::endl; } } { std::random_device rd; // 用random_device来为随机数生成器设置种子 std::mt19937_64 mt(rd()); for (int i = 0; i < 10; i++) { std::cout << mt() << std::endl; } // 整数均匀分布 std::uniform_int_distribution
     
       dis(1, 100); for (int i = 0; i < 10; i++) { std::cout << dis(mt) << std::endl; } // 浮点数均匀分布 std::uniform_real_distribution
      
        drs(0.0, 1.0); for (int i = 0; i < 10; i++) { std::cout << drs(mt) << std::endl; } } }
      
     
    
   

首页 上一页 2 3 4 5 下一页 尾页 5/5/5
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇LeetCode最常见的面试笔试题总结 下一篇C++使用Sqlite3,使用CppSQLite3..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目