Skip to content

Instantly share code, notes, and snippets.

@FONQRI
Last active November 2, 2021 16:05
Show Gist options
  • Save FONQRI/656091c5b62e119f72423c5e74e972b3 to your computer and use it in GitHub Desktop.
Save FONQRI/656091c5b62e119f72423c5e74e972b3 to your computer and use it in GitHub Desktop.
Here is an example of creating a unique id using dynamic range and counter
#include <iomanip>
#include <iostream>
#include <mutex>
#include <numeric>
#include <thread>
#include <vector>
class dynamic_range
{
public:
dynamic_range(){};
/**
* @brief acquire a range with given length
* @param length of range
* @return start of range
*/
size_t acquire(size_t length)
{
std::lock_guard<std::mutex> lg(m_mu);
if (std::numeric_limits<uint32_t>::max() - m_full_number < length)
{
throw std::out_of_range("range is done");
}
size_t start{m_full_number};
m_full_number += length;
return start;
}
private:
std::uint64_t m_full_number{0};
std::mutex m_mu;
};
int main()
{
std::vector<std::thread> thread_list;
dynamic_range dr;
auto thread_count = std::thread::hardware_concurrency();
// 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([&dr]() {
size_t all_count{0};
size_t chunk = 30000;
try
{
while (true)
{
auto start = dr.acquire(chunk);
all_count += chunk;
auto end = start + chunk - 1;
for (uint32_t i = start; i < end; ++i)
{
auto unique_number = i;
}
}
}
catch (const std::out_of_range &e)
{
std::clog << all_count << " 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