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; } } }