Browse Source

feat: building mutex in AllCases

legacy
Dnomd343 2 years ago
parent
commit
2caa33b5ab
  1. 1
      all_cases/CMakeLists.txt
  2. 42
      all_cases/all_cases.cc
  3. 5
      all_cases/all_cases.h
  4. 16
      all_cases/main.cc

1
all_cases/CMakeLists.txt

@ -2,3 +2,4 @@ cmake_minimum_required(VERSION 3.0)
set(CMAKE_CXX_STANDARD 14)
add_executable(klotski main.cc all_cases.cc)
target_link_libraries(klotski pthread)

42
all_cases/all_cases.cc

@ -1,9 +1,45 @@
#include "all_cases.h"
#include <iostream>
#include <thread>
#include <unistd.h>
std::vector<uint32_t> AllCases::basic_ranges;
bool AllCases::basic_ranges_available = false;
std::mutex AllCases::basic_ranges_building;
void AllCases::build_basic_ranges() {
AllCases::basic_ranges.emplace_back(0);
AllCases::basic_ranges.emplace_back(1);
AllCases::basic_ranges.emplace_back(2);
std::cout << std::this_thread::get_id() << " enter build function" << std::endl;
if (AllCases::basic_ranges_available) {
std::cout << std::this_thread::get_id() << " data already built -> skip" << std::endl;
return; // basic ranges already built
}
if (AllCases::basic_ranges_building.try_lock()) { // lock success -> not building
std::cout << std::this_thread::get_id() << " try lock success -> start build process" << std::endl;
AllCases::basic_ranges.emplace_back(0);
AllCases::basic_ranges.emplace_back(1);
AllCases::basic_ranges.emplace_back(2);
sleep(2); // assume using a lot of time
AllCases::basic_ranges_available = true; // enable available flag
std::cout << std::this_thread::get_id() << " build complete -> continue" << std::endl;
} else { // another thread building
std::cout << std::this_thread::get_id() << " another thread building -> wait" << std::endl;
AllCases::basic_ranges_building.lock(); // blocking wait
}
std::cout << std::this_thread::get_id() << " work complete -> unlock" << std::endl;
AllCases::basic_ranges_building.unlock();
}

5
all_cases/all_cases.h

@ -1,5 +1,6 @@
#pragma once
#include <mutex>
#include <vector>
#include <cstdint>
@ -9,4 +10,8 @@ public:
static void build_basic_ranges();
static bool basic_ranges_available;
static std::mutex basic_ranges_building;
};

16
all_cases/main.cc

@ -1,10 +1,26 @@
#include <iostream>
#include "all_cases.h"
#include <thread>
#include <unistd.h>
int main() {
std::cout << AllCases::basic_ranges.size() << std::endl;
std::thread t1(AllCases::build_basic_ranges);
usleep(100);
std::thread t2(AllCases::build_basic_ranges);
usleep(100);
std::thread t3(AllCases::build_basic_ranges);
usleep(100);
t1.join();
t2.join();
t3.join();
AllCases::build_basic_ranges();
std::cout << AllCases::basic_ranges.size() << std::endl;
return 0;

Loading…
Cancel
Save