forked from violeteverisland/learn_cpp
添加生产者消费者模型并更改了gitignore
This commit is contained in:
7
.gitignore
vendored
7
.gitignore
vendored
@@ -0,0 +1,7 @@
|
|||||||
|
# 文件夹
|
||||||
|
build/
|
||||||
|
cmake-build-debug/
|
||||||
|
.idea/
|
||||||
|
|
||||||
|
# 文件
|
||||||
|
*.exe
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
cmake_minimum_required(VERSION 4.1)
|
cmake_minimum_required(VERSION 3.30)
|
||||||
project()
|
project(main)
|
||||||
|
|
||||||
set(CMAKE_CXX_STANDARD 20)
|
set(CMAKE_CXX_STANDARD 20)
|
||||||
|
|
||||||
add_executable(main.cpp)
|
add_executable(main main.cpp)
|
||||||
|
|||||||
51
生产者消费者模型.cpp
Normal file
51
生产者消费者模型.cpp
Normal 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;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user