c++ - 多线程安全消息队列

标签 c++ multithreading

这是我的本质:

我有线程 A,它定期检查消息并处理它们。

线程B和C需要向A发送消息。

当 B 和 C 或 B 或 C 试图向 A 发送消息而 A 正在处理消息并因此访问队列时,就会出现问题。

这个问题通常是怎么解决的?

谢谢

最佳答案

这通常使用 mutexes 解决,或其他多线程保护机制。

如果您在 Windows 上工作,MFC 会提供 CMutex class对于这个问题。

如果您在 posix 系统上工作,posix api 会提供 pthread_mutex_lock, pthread_mutex_unlock, and pthread_mutex_trylock functions .

一些基本的伪代码可以很方便地演示它们在您的案例中的用途:

pthread_mutex_t mutex; *or* CMutex mutex;
Q queue;  // <-- both mutex and queue are global state, whether they are
          //     global variables, or passed in as parameters, they must
          //     be the shared by all threads.

int threadA(/* params */){
    while( threadAStillRunning ){
        // perform some non-critical actions ...
        pthread_mutex_lock(mutex) *or* mutex.Lock()
        // perform critical actions ...
        msg = queue.receiveMessage()
        pthread_mutex_unlock(mutex) *or* mutex.Unlock()
        // perform more non-critical actions
    }
}

int threadBorC(/* params */){
    while( theadBorCStillRunning ){
        // perform some non-critical actions ...
        pthread_mutex_lock(mutex) *or* mutex.Lock()
        // perform critical actions ...
        queue.sendMessage(a_msg)
        pthread_mutex_unlock(mutex) *or* mutex.Unlock()
    }
}

对于所有三个线程,它们处理队列的能力取决于它们获取互斥量的能力——它们将简单地阻塞并等待直到获取互斥量。这可以防止因使用该资源而引起的冲突。

关于c++ - 多线程安全消息队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7781747/

相关文章:

c++ - 仅在一个特定的类文件中使用命名空间

c++ - 打印奇数

c++ - 用c++解决骑士之旅

c# - 实时复制缓冲区数据

multithreading - 德尔福 11.2 : CreateWindowEx fails thread on x64

c - 多线程处理一系列方程式

c++ - 在每个类中包含相同的标题

c++ - 不再满足条件后,while 循环会停止验证吗?

java - 使用停止按钮停止 SwingWorker

java - 为什么调用 join 方法时主线程消失了?