c++中的多线程通信

信息传递

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

// 用于存储和同步数据的结构  
struct Data {
    std::queue<std::string> messages;
    std::mutex mutex;
    std::condition_variable condVar;
};

// 第一个线程函数  
void thread1(Data& data) {
    for (int i = 0; i < 10; i++) {
        std::this_thread::sleep_for(std::chrono::seconds(5));
        std::lock_guard<std::mutex> lock(data.mutex);
        data.messages.push("Hello Word!");
        data.condVar.notify_one(); // 通知第二个线程  
    }
}

// 第二个线程函数  
void thread2(Data& data) {
    while (true) {
        std::unique_lock<std::mutex> lock(data.mutex);
        data.condVar.wait(lock, [&]() { return !data.messages.empty(); }); // 等待第一个线程的通知  
        std::string message = data.messages.front();
        data.messages.pop();
        lock.unlock();
        std::cout << "Received: " << message << std::endl;
    }
}

int main() {
    Data data;
    std::thread t1(thread1, std::ref(data));
    std::thread t2(thread2, std::ref(data));
    t1.join();
    t2.detach(); // 我们希望第二个线程继续运行,所以分离它  
    return 0;
}

事件管理

#include   
#include   
#include   
#include   
#include   

class EventManager {
public:
    EventManager() {}

    void publish(int data) {
        std::unique_lock<std::mutex> lock(m_mutex);
        m_dataQueue.push(data);
        m_cond.notify_all();
    }

    int subscribe() {
        std::unique_lock<std::mutex> lock(m_mutex);
        while (m_dataQueue.empty()) {
            m_cond.wait(lock);
        }
        int data = m_dataQueue.front();
        m_dataQueue.pop();
        return data;
    }

private:
    std::mutex m_mutex;
    std::condition_variable m_cond;
    std::queue<int> m_dataQueue;
};

void threadFunction1(EventManager& eventManager) {
    for (int i = 1; i <= 10; ++i) {
        eventManager.publish(i);
        std::cout << "Thread 1 published data: " << i << std::endl;
    }
}

void threadFunction2(EventManager& eventManager) {
    for (int i = 1; i <= 10; ++i) {
        int data = eventManager.subscribe();
        std::cout << "Thread 2 subscribed data: " << data << std::endl;
    }
}

int main() {
    EventManager eventManager;
    std::thread thread1(threadFunction1, std::ref(eventManager));
    std::thread thread2(threadFunction2, std::ref(eventManager));
    thread1.join();
    thread2.join();
    return 0;
}

你可能感兴趣的:(c++)