例子

    1. #include <iostream>
    2. #include <thread>
    3. #include <atomic>
    4. #include <vector>
    5. std::atomic<long long> data;
    6. long long _data = 0;
    7. void do_work()
    8. {
    9. //_data++;
    10. data.fetch_add(1, std::memory_order_relaxed);
    11. }
    12. int main()
    13. {
    14. std::vector<std::thread> thread_pool;
    15. for (int i = 0; i < 1000; i++) {
    16. std::thread t(do_work);
    17. thread_pool.push_back(std::move(t));
    18. }
    19. for (int i = 0 ; i < 1000 ; i++) {
    20. thread_pool[i].join();
    21. }
    22. //std::cout << "Result:" << _data << '\n';
    23. std::cout << "Result:" << data << '\n';
    24. }