1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| #include <queue> #include <mutex> #include <condition_variable> #include <thread> #include <iostream> #include <atomic>
template <typename T> class ProducerConsumer { private: std::queue<T> taskQ; std::condition_variable isFull; std::condition_variable isEmpty; std::mutex mtx; size_t maxSize; std::atomic<bool> stop;
std::vector<std::thread> pThreads; std::vector<std::thread> cThreads;
auto Do(T task) { std::cout << "消费了一个任务" << std::endl; return; }
public: ProducerConsumer(size_t size) :maxSize{ size }, stop{ false } {}
void Producer(const T& task) { std::unique_lock<std::mutex> lock(mtx); isFull.wait(lock, [this]() { return taskQ.size() < maxSize || stop; }); if (stop) return; taskQ.emplace(task); isEmpty.notify_one(); }
void Consumer() { std::unique_lock<std::mutex> lock(mtx); isEmpty.wait(lock, [this]() { return !taskQ.empty() || stop; }); if (taskQ.empty() && stop) return; auto temp = taskQ.front(); taskQ.pop(); lock.unlock(); Do(temp); isFull.notify_one(); } };
int main() {
return 0; }
|