Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

吕宇浩 #3

Open
IKUNNBBBB opened this issue Nov 29, 2023 · 0 comments
Open

吕宇浩 #3

IKUNNBBBB opened this issue Nov 29, 2023 · 0 comments

Comments

@IKUNNBBBB
Copy link

IKUNNBBBB commented Nov 29, 2023

#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;
}
@IKUNNBBBB IKUNNBBBB reopened this Nov 29, 2023
@IKUNNBBBB IKUNNBBBB reopened this Nov 29, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant