具有多个线程的安全消息队列

jma*_*erx 6 c++ multithreading

这是我基本上拥有的:

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

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

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

这个问题通常如何解决?

谢谢

Nat*_*ate 4

这通常可以使用互斥体或其他多线程保护机制来解决。

如果您在 Windows 上工作,MFC 提供了CMutex 类来解决此问题。

如果您使用 posix 系统,则 posix api 提供pthread_mutex_lockpthread_mutex_unlockpthread_mutex_trylock函数

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

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()
    }
}
Run Code Online (Sandbox Code Playgroud)

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

  • @Nate:我从未听说过有关关键部分的哲学论证。它们通常用于数据同步。 (2认同)