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

黄秋潭 #4

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

黄秋潭 #4

josidhuang opened this issue Nov 29, 2023 · 0 comments

Comments

@josidhuang
Copy link

josidhuang commented Nov 29, 2023

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <stdlib.h>

std::mutex mtx;
std::condition_variable cv;
std::queue<int> dataQueue;
bool isDataAvailable = false;
bool stopFlag = false;

void publisher() {
    while (!stopFlag) {
        std::unique_lock<std::mutex> lock(mtx);

        int ran = rand() % 100 + 1;

        dataQueue.push(ran);
        isDataAvailable = true;
       printf( "发布:%d\n",ran);

        cv.notify_all();
lock.unlock();
        std::this_thread::sleep_for(std::chrono::seconds(2));
    }
}


void subscriber(int id) {
        std::unique_lock<std::mutex> lock(mtx);

        cv.wait(lock, [] { return isDataAvailable || stopFlag; });

        int data = dataQueue.front();
        dataQueue.pop();

        if (data % 2 == 0) {
            printf("订阅%d:%d\n",id,data);
        }
lock.unlock();
        isDataAvailable = false;
    
}

int main() {
    std::thread publisherThread(publisher);
    std::thread subscriberThread1(subscriber,1);
    std::thread subscriberThread2(subscriber,2);

    std::cout << "回车停止。" << std::endl;
    std::getchar();  
    stopFlag = true;

    publisherThread.join();
    subscriberThread1.join();
    subscriberThread2.join();

    return 0;
}
  • 问题:怎么让订阅1和订阅2分别处理数据
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