添加生产者消费者模型并更改了gitignore

This commit is contained in:
Jacky
2026-02-23 21:34:00 +08:00
parent e1e9babaa0
commit 06fa0c1609
3 changed files with 61 additions and 3 deletions

7
.gitignore vendored
View File

@@ -0,0 +1,7 @@
# 文件夹
build/
cmake-build-debug/
.idea/
# 文件
*.exe

View File

@@ -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)

View File

@@ -0,0 +1,51 @@
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <queue>
#include <thread>
int main() {
std::condition_variable cv;
std::mutex mtx;
std::queue<int> 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<std::mutex> lock(mtx);
q.push(i);
std::cout << "Produced: " << i << "\n";
}
cv.notify_one();
}
{
std::lock_guard<std::mutex> lock(mtx);
finished = true;
}
cv.notify_all();
};
auto consumer = [&]() {
while (true) {
std::unique_lock<std::mutex> 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;
}