Last active
October 21, 2021 06:31
-
-
Save FONQRI/da1b2c3a73cc7d6f835d6847da0e4e41 to your computer and use it in GitHub Desktop.
Here is a bad example of creating unique counter id with atomics for blog post
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <atomic> | |
#include <iomanip> | |
#include <iostream> | |
#include <numeric> | |
#include <thread> | |
#include <vector> | |
int main() | |
{ | |
std::atomic_int32_t counter{0}; | |
// std::atomic_int64_t all_counted_numbers_count{0}; | |
std::vector<std::thread> thread_list; | |
auto thread_count = std::thread::hardware_concurrency(); | |
// NOTE In the worst case,this way will lose thread_count-1 number, but doesn't matter | |
auto count_per_thread = std::numeric_limits<uint32_t>::max() / thread_count - 1; | |
// record start time | |
auto start = std::chrono::high_resolution_clock::now(); | |
for (uint8_t i = 0; i < thread_count; ++i) | |
{ | |
thread_list.push_back(std::thread([&counter, count_per_thread]() { | |
for (uint32_t i = 0; i < count_per_thread; ++i) | |
{ | |
auto unique_number = counter++; | |
} | |
std::clog << count_per_thread << " done" << std::endl; | |
})); | |
} | |
for (auto &thread : thread_list) | |
{ | |
if (thread.joinable()) | |
{ | |
thread.join(); | |
} | |
} | |
std::cout << "time of all threads " << std::setw(9) | |
<< std::chrono::duration<double>(std::chrono::high_resolution_clock::now() - start) | |
.count() | |
<< " s\n"; | |
std::cout << "Hello World!" << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment