zoukankan      html  css  js  c++  java
  • c++11 std::atomic 原子操作

    The main characteristic of atomic objects is that access to this contained value from different threads cannot cause data races。

    提供对基本内建数据的互斥访问。

    // atomic::exchange example
    #include <iostream>       // std::cout
    #include <atomic>         // std::atomic
    #include <thread>         // std::thread
    #include <vector>         // std::vector
    
    std::atomic<bool> ready (false);
    std::atomic<bool> winner (false);
    
    void count1m (int id) {
      while (!ready) {}                  // wait for the ready signal
      
     for (int i=0; i<1000000; ++i)
    {} // go!, count to 1 million
     if (!winner.exchange(true))
     {
      std::cout << "thread #" << id << " won! "; 、
    } };
    int main () { std::vector<std::thread> threads; std::cout << "spawning 10 threads that count to 1 million... "; for (int i=1; i<=10; ++i) threads.push_back(std::thread(count1m,i)); ready = true; for (auto& th : threads) th.join(); return 0; }
  • 相关阅读:
    最短路径问题/Spfa
    cddiv/数组维护
    cfdiv2/c/找规律
    Codeforces Round #343 (Div. 2)【A,B水题】
    POJ 2135_Farm Tour
    POJ 3469_Dual Core CPU
    POJ 3469_Dual Core CPU
    POJ 3281_Dining
    POJ 3281_Dining
    POJ 3041_Asteroids
  • 原文地址:https://www.cnblogs.com/rayfloyd/p/14306595.html
Copyright © 2011-2022 走看看