Skip to content

吕宇浩 #3

@IKUNNBBBB

Description

@IKUNNBBBB
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <vector>
#include <ctime>
#include <cstdlib>

std::mutex mtx;
std::condition_variable cv;
std::vector<int> data;
bool has_data = false;

void publisher() {
    while (true) {
        std::unique_lock<std::mutex> lock(mtx);
        int random_num = rand() % 100 + 1;
        data.push_back(random_num);
        has_data = true;
        std::cout << "Publisher published: " << random_num << std::endl;
        cv.notify_all();
        lock.unlock();
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
}

void subscriber() {
    while (true) {
        std::unique_lock<std::mutex> lock(mtx);
        cv.wait(lock, [] { return has_data; });
        for (int num : data) {
            if (num % 2 == 0) {
                std::cout << "Subscriber received number: " << num << std::endl;
            }
        }
        data.clear();
        has_data = false;
        lock.unlock();
    }
}

int main() {
    srand(time(0));
    std::thread pub(publisher);
    std::thread sub(subscriber);
    pub.join();
    sub.join();
    return 0;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions