Skip to content

黄秋潭 #4

Description

@josidhuang
#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分别处理数据

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