这是我基本上拥有的:
我有线程 A 定期检查消息并处理它们。
线程B和C需要向A发送消息。
当 B 和 C 或 B 或 C 尝试向 A 发送消息,而 A 正在处理消息并访问队列时,就会出现问题。
这个问题通常是如何解决的?
Thanks
这通常可以使用以下方法解决mutexes http://en.wikipedia.org/wiki/Mutex,或者其他多线程保护机制。
如果您在 Windows 上工作,MFC 提供了CMutex 类 http://msdn.microsoft.com/en-us/library/tt45160e%28v=vs.80%29.aspx对于这个问题。
如果您正在使用 posix 系统,则 posix api 提供pthread_mutex_lock, pthread_mutex_unlock, and pthread_mutex_trylock功能 https://computing.llnl.gov/tutorials/pthreads/#MutexLocking.
一些基本的伪代码可以很方便地演示它们在您的案例中的用途:
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()
}
}
对于所有三个线程,它们对队列进行操作的能力取决于它们获取互斥体的能力 - 它们将简单地阻塞并等待,直到获取互斥体。这可以防止因使用该资源而引起的冲突。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)