From 06fa0c1609681eef42415cfb8e8eb7b70b819829 Mon Sep 17 00:00:00 2001 From: Jacky Date: Mon, 23 Feb 2026 21:34:00 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E7=94=9F=E4=BA=A7=E8=80=85?= =?UTF-8?q?=E6=B6=88=E8=B4=B9=E8=80=85=E6=A8=A1=E5=9E=8B=E5=B9=B6=E6=9B=B4?= =?UTF-8?q?=E6=94=B9=E4=BA=86gitignore?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 7 ++++++ CMakeLists.txt | 6 +++--- 生产者消费者模型.cpp | 51 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 61 insertions(+), 3 deletions(-) create mode 100644 生产者消费者模型.cpp 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