具有多个线程的安全消息队列 [英] Safe Message Queue with multiple threads

查看:132
本文介绍了具有多个线程的安全消息队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是我本质上有:



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



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



当B和C或B或C尝试向A发送消息时出现问题,而A



这个问题通常是如何解决的?



感谢

解决方案

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



如果您正在使用Windows,MFC会提供 CMutex类此问题。



如果您使用的是posix系统,则posix api提供 pthread_mutex_lock pthread_mutex_unlock pthread_mutex_trylock p>

一些基本的伪代码将很方便地展示它们在你的情况下的使用:

  pthread_mutex_t mutex; *或* CMutex mutex; 
Q queue; //< - mutex和queue都是全局状态,无论它们是
//全局变量还是作为参数传递,它们必须
//被所有线程共享。

int threadA(/ * params * /){
while(threadAStillRunning){
//执行一些非关键操作...
pthread_mutex_lock *或* mutex.Lock()
//执行关键操作...
msg = queue.receiveMessage()
pthread_mutex_unlock(mutex)*或* mutex.Unlock b //执行更多非关键操作
}
}

int threadBorC(/ * params * /){
while(theadBorCStillRunning){
//执行一些非关键操作...
puesread_mutex_lock(mutex)*或* mutex.Lock()
//执行关键操作...
queue.sendMessage(a_msg)
pthread_mutex_unlock(mutex)* or * mutex.Unlock()
}
}


$ b b

对于所有三个线程,它们对队列行动的能力取决于它们获取互斥体的能力 - 它们将简单地阻塞并等待互斥体被获取。这可以防止因使用该资源而产生的冲突。


Here is what I essentially have:

I have thread A that periodically checks for messages and processes them.

Threads B and C need to send messages to A.

The problem arises when B and C or B or C try to send a message to A while A is processing a message and thus accessing the queue.

How is this problem usually solved?

Thanks

解决方案

This is normally solved using mutexes, or other multi-thread protection mechanisms.

If you are working on windows, MFC provides the CMutex class for this problem.

If you are working on a posix system, the posix api provides the pthread_mutex_lock, pthread_mutex_unlock, and pthread_mutex_trylock functions.

Some basic pseudocode would be handy to demonstrate their use in your case:

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()
    }
}

For all three threads, their ability to act on the queue hinges on their ability to acquire the mutex - they will simply block and wait until the mutex is acquired. This prevents conflicts arising from the use of that resource.

这篇关于具有多个线程的安全消息队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆