Skip to content

Instantly share code, notes, and snippets.

@FONQRI
Last active November 2, 2021 16:04
Show Gist options
  • Save FONQRI/b987354ae60e5fb671d7d929ff14e6d1 to your computer and use it in GitHub Desktop.
Save FONQRI/b987354ae60e5fb671d7d929ff14e6d1 to your computer and use it in GitHub Desktop.
Here is an example of creating a unique id using fix range and counter
#include <iomanip>
#include <iostream>
#include <numeric>
#include <thread>
#include <vector>
int main()
{
std::vector<std::thread> thread_list;
auto thread_count = std::thread::hardware_concurrency();
size_t thread_results = thread_count;
// 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)
{
std::pair<size_t, size_t> range(count_per_thread * i,
count_per_thread * i + count_per_thread - 1);
thread_list.push_back(std::thread([range, count_per_thread]() {
auto [start, end] = range;
uint32_t uniue_number{0};
for (uint32_t i = 0; i < count_per_thread; ++i)
{
uniue_number = i;
}
std::clog << uniue_number << " 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