diff --git a/.gitignore b/.gitignore index e69de29..c5b5e25 100644 --- a/.gitignore +++ b/.gitignore @@ -0,0 +1,7 @@ +# 文件夹 +build/ +cmake-build-debug/ +.idea/ + +# 文件 +*.exe \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt index 64e6be4..d818b08 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,6 +1,6 @@ -cmake_minimum_required(VERSION 4.1) -project() +cmake_minimum_required(VERSION 3.30) +project(main) set(CMAKE_CXX_STANDARD 20) -add_executable(main.cpp) +add_executable(main main.cpp) diff --git a/生产者消费者模型.cpp b/生产者消费者模型.cpp new file mode 100644 index 0000000..2811c8f --- /dev/null +++ b/生产者消费者模型.cpp @@ -0,0 +1,51 @@ +#include +#include +#include +#include +#include + +int main() { + std::condition_variable cv; + std::mutex mtx; + std::queue q; + bool finished = false; + + auto producer = [&]() { + for (int i = 0; i < 10; i++) { + std::this_thread::sleep_for(std::chrono::milliseconds(200)); + { + std::lock_guard lock(mtx); + q.push(i); + std::cout << "Produced: " << i << "\n"; + } + cv.notify_one(); + } + { + std::lock_guard lock(mtx); + finished = true; + } + cv.notify_all(); + }; + + auto consumer = [&]() { + while (true) { + std::unique_lock lock(mtx); + cv.wait(lock, [&]() { return !q.empty() || finished; }); + if (!q.empty()) { + int i = q.front(); + q.pop(); + lock.unlock(); + std::cout << "Consumed: "<< i << "\n"; + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + } else if (q.empty() && finished) { + break; + } + } + }; + + std::thread t1(producer); + std::thread t2(consumer); + t1.join(); + t2.join(); + return 0; +} \ No newline at end of file