本文介绍了多线程观察者模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,每次主题都在不同的线程中更新.因此,无论何时更新主题,它都会相应地用新信息更新观察者.但是,如果观察者列表很长,那么将需要一些时间来更新所有观察者.考虑一个经常更新的主题.当主题正在更新观察者时,主题"对象被锁定,因此无法通过其他线程进行更新.这将为主题创建信息流量,或者导致信息丢失.

I have a question where a subject is updated in a different thread every time. So whenever the subject is updated it correspondingly updates the observer with the new information. However, if the list of observers is long, it will require some time to update all the observers. Think of a subject that gets updated very frequently. While the subject is updating the observers, "subject" object is locked and hence cannot be updated by a different thread. This will either create information traffic for subject or cause loss of information.

您是否知道在多线程环境中如何处理这些问题?另外,有人可以推荐一些有关使用C ++进行并行编程的书吗?

Do you have any idea how these issues are handled in a multi-threaded environment? Also, Can anyone recommend some books on parallel programming with C++?

推荐答案

请考虑使用 producer-消费者队列消息队列.对于您的示例,您可以通过两种方式使用队列:

Consider the use of producer-consumer queues or message queues. For your example, you can use a queue in two ways:

  1. 对主题的更改已排队.当某些事物更新主题时,它将新状态放入队列并立即返回.这样,在通知观察者的同时,更新程序不会阻塞.您将需要一个线程,该线程会不断使状态更改出队并更新观察者.

  1. Changes to the Subject are queued. When something updates the subject, it puts the new state in the queue and returns immediately. This way, the updater does not block while the observers are notified. You will need a thread that continuously dequeues state changes and updates observers.

对观察者的通知已排队.每个观察者都有一个队列,其中张贴主题状态更改通知.

Notifications to Observers are queued. Each observer has a queue where subject state-change notifications are posted.

如果您使用的是Qt库,则可以使用信号&具有 Qt :: QueuedConnection 连接的广告位机制类型.该插槽通过接收方的事件队列,并在接收方的线程中执行.这样,发送方不会在接收方执行各自的插槽时阻塞.

If you are using the Qt library, you can use the signals & slots mechanism with the Qt::QueuedConnection connection type. The slot goes through the receiver's event queue and is executed in the receiver's thread. This way, the sender does not block while the receivers execute their respective slots.

您的程序可能是演员模型(范例)的很好的候选人.这里是一些实现actor模型的C ++库:

Your program might be a good candidate for the Actor model (paradigm). Here are some C++ libraries that implement the actor model:

  • Theron
  • libcppa (C++11 based)
  • Asynchronous Agents Library (Microsoft)

您的程序也可能是数据流范式的理想人选.查看建议的 Boost Dataflow 库,该库支持线程化.

Your program might also be a good candidate for the Dataflow paradigm. Check out the proposed Boost Dataflow library, which supports threading.

我没有一本值得推荐的书,但请查看Herb Sutter的 Dobbs博士系列文章关于C ++并发性.

I don't have a book to recommend, but check out Herb Sutter's series of Dr Dobbs articles on C++ concurrency.

这篇关于多线程观察者模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 19:01