基于 定长阻塞 消息队列 实现的发布订阅模式[c++]

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

// 自定义消息结构
template 
struct CustomMessage {
    CallbackType callback;
    void* data;
    size_t length;

    CustomMessage(CallbackType callback, void* data, size_t length)
        : callback(callback), data(data), length(length) {}

    CustomMessage() = default; // 添加默认构造函数
};

// 消息队列
template 
class MessageQueue {
public:
    void push(const CustomMessage& message) {
        std::unique_lock lock(mutex);
        while (queue.size() >= maxQueueSize) {
            // 队列已满,等待
            notFull.wait(lock);
        }
        queue.push(message);
        lock.unlock();
        notEmpty.notify_one(); // 通知观察者队列不为空
    }

    bool pop(CustomMessage& message) {
        std::unique_lock lock(mutex);
        while (queue.empty() && !finished) {
            // 队列为空且未完成,等待
            notEmpty.wait(lock);
        }
        if (!queue.empty()) {
            message = queue.front();
            queue.pop();
            lock.unlock();
            notFull.notify_one(); // 通知发布者队列不满
            return true;
        }
        return false;
    }

    void setFinished() {
        std::unique_lock lock(mutex);
        finished = true;
        lock.unlock();
        notEmpty.notify_all(); // 唤醒等待的观察者线程
    }

private:
    std::queue> queue;
    const size_t maxQueueSize = 5; // 队列最大容量
    bool finished = false;
    std::mutex mutex;
    std::condition_variable notEmpty;
    std::condition_variable notFull;
};

// 抽象观察者
template 
class Observer {
public:
    virtual void update(const CustomMessage& message) = 0;
};

// 具体观察者
template 
class ConcreteObserver : public Observer {
public:
    ConcreteObserver(const std::string& name, MessageQueue& messageQueue)
        : name(name), messageQueue(messageQueue) {}

    void update(const CustomMessage& message) override {
        std::this_thread::sleep_for(std::chrono::seconds(3));
        std::cout << name << " 收到消息,长度: " << message.length << std::endl;
        // 处理消息
        message.callback(message.data, message.length);
        std::this_thread::sleep_for(std::chrono::seconds(3));

    }

    void start() {
        while (true) {
            CustomMessage message;
            if (messageQueue.pop(message)) {
                update(message);
            } else {
                break; // 队列已完成
            }
        }
    }

private:
    std::string name;
    MessageQueue& messageQueue;
};

// 具体发布者
template 
class Publisher {
public:
    Publisher(MessageQueue& messageQueue) : messageQueue(messageQueue) {}

    void publishMessages(const std::vector>& messages) {
        for (const CustomMessage& message : messages) {
            messageQueue.push(message);
        }
        messageQueue.setFinished();
    }

private:
    MessageQueue& messageQueue;
};

int main() {
    MessageQueue> messageQueue;
    Publisher> publisher(messageQueue);

    ConcreteObserver> observer1("观察者1", messageQueue);
    ConcreteObserver> observer2("观察者2", messageQueue);

    // 示例回调函数
    auto callback = [](void* data, size_t length) {
        char* messageData = static_cast(data);
        std::cout << "回调函数处理消息数据: " << std::string(messageData, length) << std::endl;
    };
    std::vector>> messages;
    char messageData[] = "自定义消息";
    CustomMessage> customMessage(callback, messageData, strlen(messageData));
    messages.push_back(customMessage);
    messages.push_back(customMessage);
    messages.push_back(customMessage);
    messages.push_back(customMessage);
    messages.push_back(customMessage);
    messages.push_back(customMessage);
    messages.push_back(customMessage);

    std::thread([&]() {
        publisher.publishMessages(messages);
    }).detach();

    std::thread observerThread1(&ConcreteObserver>::start, &observer1);
    std::thread observerThread2(&ConcreteObserver>::start, &observer2);

    observerThread1.join();
    observerThread2.join();

    return 0;
}
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

// 自定义消息结构
template 
struct CustomMessage {
    CallbackType callback;
    void* data;
    size_t length;

    CustomMessage(CallbackType callback, void* data, size_t length)
        : callback(callback), data(data), length(length) {}

    CustomMessage() = default;
};

// 消息队列
template 
class MessageQueue {
public:
    void push(const CustomMessage& message) {
        std::unique_lock lock(mutex);
        while (queue.size() >= maxQueueSize) {
            notFull.wait(lock);
        }
        queue.push(message);
        lock.unlock();
        notEmpty.notify_one();
    }

    bool pop(CustomMessage& message) {
        std::unique_lock lock(mutex);
        while (queue.empty() && !finished) {
            notEmpty.wait(lock);
        }
        if (!queue.empty()) {
            message = queue.front();
            queue.pop();
            lock.unlock();
            notFull.notify_one();
            return true;
        }
        return false;
    }

    void setFinished() {
        std::unique_lock lock(mutex);
        finished = true;
        lock.unlock();
        notEmpty.notify_all();
    }

private:
    std::queue> queue;
    const size_t maxQueueSize = 5;
    bool finished = false;
    std::mutex mutex;
    std::condition_variable notEmpty;
    std::condition_variable notFull;
};

// 抽象观察者
template 
class Observer {
public:
    virtual void update(const CustomMessage& message) = 0;
};

// 具体观察者
template 
class ConcreteObserver : public Observer {
public:
    ConcreteObserver(const std::string& name)
        : name(name) {}

    void update(const CustomMessage& message) override {
        std::cout << name << " 收到消息,长度: " << message.length << std::endl;
        message.callback(message.data, message.length);
    }

private:
    std::string name;
};

// 具体发布者
template 
class Publisher {
public:
    Publisher(MessageQueue& messageQueue) : messageQueue(messageQueue) {}

    void publishMessages(const std::vector>& messages) {
        for (const CustomMessage& message : messages) {
            messageQueue.push(message);
        }
        messageQueue.setFinished();
    }

private:
    MessageQueue& messageQueue;
};

// 具体主题
template 
class ConcreteSubject {
public:
    void addObserver(Observer* observer) {
        observers.push_back(observer);
    }

    void removeObserver(Observer* observer) {
        auto it = std::find(observers.begin(), observers.end(), observer);
        if (it != observers.end()) {
            observers.erase(it);
        }
    }

    void notifyObservers() {
        while (true) {
            CustomMessage message;
            if (messageQueue.pop(message)) {
                for (Observer* observer : observers) {
                    observer->update(message);
                }
            } else {
                break;
            }
        }
    }

    void startObservers() {
        for (Observer* observer : observers) {
            observerThreads.push_back(std::thread(&ConcreteSubject::runObserver, this, observer));
        }
    }

    void joinObservers() {
        for (std::thread& thread : observerThreads) {
            thread.join();
        }
    }

    void runObserver(Observer* observer) {
        // 观察者线程等待消息
        CustomMessage message;
        while (messageQueue.pop(message)) {
            observer->update(message);
        }
    }

    MessageQueue& getMessageQueue() { return messageQueue; }

private:
    std::vector*> observers;
    MessageQueue messageQueue;
    std::vector observerThreads;
};

int main() {
    ConcreteSubject> subject;

    ConcreteObserver> observer1("观察者1");
    ConcreteObserver> observer2("观察者2");

    subject.addObserver(&observer1);
    subject.addObserver(&observer2);



    char messageData[] = "自定义消息"; // ??????????
    std::thread([&]() {
    auto callback = [](void* data, size_t length) {
        char* messageData = static_cast(data);
        std::cout << "回调函数处理消息数据: " << std::string(messageData, length) << std::endl;
    };
    CustomMessage> customMessage(callback, messageData, strlen(messageData));
    std::vector>> messages;
    messages.push_back(customMessage);
    messages.push_back(customMessage);
    messages.push_back(customMessage);
    messages.push_back(customMessage);
    messages.push_back(customMessage);
    messages.push_back(customMessage);
        Publisher> publisher(subject.getMessageQueue());
        publisher.publishMessages(messages);
    }).detach();

    subject.startObservers();
    subject.joinObservers();

    return 0;
}

你可能感兴趣的:(c++,算法,开发语言)