From a225cde56e09f16485f2ee2b377d03b18c7d5002 Mon Sep 17 00:00:00 2001 From: Dnomd343 Date: Sun, 8 Jan 2023 11:25:00 +0800 Subject: [PATCH] feat: get basic ranges status --- all_cases/basic_ranges.cc | 11 +++++++++++ all_cases/basic_ranges.h | 9 --------- all_cases/main.cc | 22 +++++++++++++++++++++- 3 files changed, 32 insertions(+), 10 deletions(-) diff --git a/all_cases/basic_ranges.cc b/all_cases/basic_ranges.cc index 40bb413..c07ce7c 100644 --- a/all_cases/basic_ranges.cc +++ b/all_cases/basic_ranges.cc @@ -15,6 +15,17 @@ inline uint32_t binary_count(uint32_t bin) { // get number of non-zero bits return bin & 0b111111; } +BasicRanges::Status BasicRanges::basic_ranges_status() { // get basic ranges status + if (basic_ranges_available) { + return AVAILABLE; // basic ranges already built + } + if (!basic_ranges_building.try_lock()) { // fail to lock mutex -> another thread working + return BUILDING; + } + basic_ranges_building.unlock(); // release mutex + return NO_INIT; +} + const std::vector* BasicRanges::get_basic_ranges() { // get const ptr of basic ranges if (basic_ranges.empty()) { build_basic_ranges(); // basic ranges initialize diff --git a/all_cases/basic_ranges.h b/all_cases/basic_ranges.h index ade275c..85a8b29 100644 --- a/all_cases/basic_ranges.h +++ b/all_cases/basic_ranges.h @@ -6,27 +6,18 @@ class BasicRanges { public: - enum Status { NO_INIT, BUILDING, AVAILABLE, }; - static void build_basic_ranges(); - static enum Status basic_ranges_status(); - static const std::vector* get_basic_ranges(); private: - static bool basic_ranges_available; - static std::mutex basic_ranges_building; - static std::vector basic_ranges; - static void generate_ranges(int n1, int n2, int n3, int n4); - }; diff --git a/all_cases/main.cc b/all_cases/main.cc index 9b2b963..32d8073 100644 --- a/all_cases/main.cc +++ b/all_cases/main.cc @@ -4,15 +4,35 @@ #include +void get_status() { + switch (BasicRanges::basic_ranges_status()) { + case BasicRanges::NO_INIT: + std::cout << "basic ranges no init" << std::endl; + break; + case BasicRanges::BUILDING: + std::cout << "basic ranges building" << std::endl; + break; + case BasicRanges::AVAILABLE: + std::cout << "basic ranges available" << std::endl; + break; + } +} + int main() { + + get_status(); + std::thread t1(BasicRanges::build_basic_ranges); std::thread t2(BasicRanges::build_basic_ranges); std::thread t3(BasicRanges::build_basic_ranges); + std::thread t(get_status); t1.join(); t2.join(); t3.join(); + t.join(); + + get_status(); -// BasicRanges::build_basic_ranges(); std::cout << BasicRanges::get_basic_ranges()->size() << std::endl; return 0;