12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- #include <queue>
- #include <thread>
- #include <mutex>
- #include <condition_variable>
- #include <functional>
- class DataProcessor {
- public:
- using DataHandler = std::function<void(const std::string&)>;
- DataProcessor() : m_running(true), m_worker([this] { processData(); }) {}
- ~DataProcessor() {
- {
- std::lock_guard<std::mutex> lock(m_mutex);
- m_running = false;
- m_Condition_.notify_one();
- }
- m_worker.join();
- }
- void setDataHandler(DataHandler handler) {
- m_handler = std::move(handler);
- }
- void receiveData(const std::string& data) {
- {
- std::lock_guard<std::mutex> lock(m_mutex);
- m_dataQueue.push(data);
- }
- m_Condition_.notify_one();
- }
- private:
- void processData() {
- while (true) {
- std::unique_lock<std::mutex> lock(m_mutex);
- m_Condition_.wait(lock, [this] {
- return !m_running || !m_dataQueue.empty();
- });
- if (!m_running && m_dataQueue.empty()) {
- break;
- }
- if (!m_dataQueue.empty()) {
- auto data = m_dataQueue.front();
- m_dataQueue.pop();
- lock.unlock();
- if (m_handler) {
- m_handler(data);
- }
- }
- }
- }
- std::queue<std::string> m_dataQueue;
- std::mutex m_mutex;
- std::condition_variable m_Condition_;
- DataHandler m_handler;
- bool m_running;
- std::thread m_worker;
- };
|