在C ++中进行事件处理的正确方法是什么?

时间:2012-03-14 22:41:48

标签: c++ multithreading events event-handling

我有一个应用程序需要以下列方式响应某些事件:

void someMethodWithinSomeClass() {
    while (true) {
        wait for event;
        if (event == SomeEvent) {
            doSomething();
            continue;
        }
        if (event == SomeOtherEvent) {
            doSomethingElse();
            continue;
        }
    } 
}

这将是一些线程运行。在其他一些线程中,操作会创建并触发事件。

如何让这些事件达到上述方法/类?在C ++中实现事件处理的正确策略或体系结构是什么?

4 个答案:

答案 0 :(得分:12)

通常,事件队列实现为command design pattern

  

在面向对象的编程中,命令模式是一种设计   一个对象用于表示和封装所有对象的模式   稍后调用方法所需的信息。这个   信息包括方法名称,拥有该方法的对象   和方法参数的值。

在C ++中,拥有方法的对象和方法参数的值是一个无效的仿函数(即不带参数的仿函数)。它可以使用boost::bind()C++11 lambdas创建,并包含在boost::function中。

这是一个如何在多个生产者和多个消费者线程之间实现事件队列的极简主义示例。用法:

void consumer_thread_function(EventQueue::Ptr event_queue)
try {
    for(;;) {
        EventQueue::Event event(event_queue->consume()); // get a new event 
        event(); // and invoke it
    }
}
catch(EventQueue::Stopped&) {
}

void some_work(int n) {
    std::cout << "thread " << boost::this_thread::get_id() << " : " << n << '\n';
    boost::this_thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(500));
}

int main()
{
    some_work(1);

    // create an event queue that can be shared between multiple produces and multiple consumers
    EventQueue::Ptr queue(new EventQueue);

    // create two worker thread and pass them a pointer to queue
    boost::thread worker_thread_1(consumer_thread_function, queue);
    boost::thread worker_thread_2(consumer_thread_function, queue);

    // tell the worker threads to do something
    queue->produce(boost::bind(some_work, 2));
    queue->produce(boost::bind(some_work, 3));
    queue->produce(boost::bind(some_work, 4));

    // tell the queue to stop
    queue->stop(true);

    // wait till the workers thread stopped
    worker_thread_2.join();
    worker_thread_1.join();

    some_work(5);
}

输出:

./test
thread 0xa08030 : 1
thread 0xa08d40 : 2
thread 0xa08fc0 : 3
thread 0xa08d40 : 4
thread 0xa08030 : 5

实现:

#include <boost/function.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/condition.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/smart_ptr/intrusive_ptr.hpp>
#include <boost/smart_ptr/detail/atomic_count.hpp>
#include <iostream>

class EventQueue
{
public:
    typedef boost::intrusive_ptr<EventQueue> Ptr;
    typedef boost::function<void()> Event; // nullary functor
    struct Stopped {};

    EventQueue()
        : state_(STATE_READY)
        , ref_count_(0)
    {}

    void produce(Event event) {
        boost::mutex::scoped_lock lock(mtx_);
        assert(STATE_READY == state_);
        q_.push_back(event);
        cnd_.notify_one();
    }

    Event consume() {
        boost::mutex::scoped_lock lock(mtx_);
        while(STATE_READY == state_ && q_.empty())
            cnd_.wait(lock);
        if(!q_.empty()) {
            Event event(q_.front());
            q_.pop_front();
            return event;
        }
        // The queue has been stopped. Notify the waiting thread blocked in
        // EventQueue::stop(true) (if any) that the queue is empty now.
        cnd_.notify_all();
        throw Stopped();
    }

    void stop(bool wait_completion) {
        boost::mutex::scoped_lock lock(mtx_);
        state_ = STATE_STOPPED;
        cnd_.notify_all();
        if(wait_completion) {
            // Wait till all events have been consumed.
            while(!q_.empty())
                cnd_.wait(lock);
        }
        else {
            // Cancel all pending events.
            q_.clear();
        }
    }

private:
    // Disable construction on the stack. Because the event queue can be shared between multiple
    // producers and multiple consumers it must not be destroyed before the last reference to it
    // is released. This is best done through using a thread-safe smart pointer with shared
    // ownership semantics. Hence EventQueue must be allocated on the heap and held through
    // smart pointer EventQueue::Ptr.
    ~EventQueue() {
        this->stop(false);
    }

    friend void intrusive_ptr_add_ref(EventQueue* p) {
        ++p->ref_count_;
    }

    friend void intrusive_ptr_release(EventQueue* p) {
        if(!--p->ref_count_)
            delete p;
    }

    enum State {
        STATE_READY,
        STATE_STOPPED,
    };

    typedef std::list<Event> Queue;
    boost::mutex mtx_;
    boost::condition_variable cnd_;
    Queue q_;
    State state_;
    boost::detail::atomic_count ref_count_;
};

答案 1 :(得分:10)

C ++标准根本不涉及事件。但是,通常情况下,如果您需要事件,则可以在提供事件的框架内工作(SDL,Windows,Qt,GNOME等)以及等待,调度和使用它们的方法。

除此之外,您可能需要查看Boost.Signals2

答案 2 :(得分:7)

C ++ 11和Boost有condition variables。它们是线程取消阻止等待某个事件发生的另一个线程的手段。上面的链接将您带到boost::condition_variable的文档,并有一个代码示例,说明如何使用它。

如果你需要跟踪事件(比如击键)并需要以FIFO(先进先出)的方式处理它们,那么你将不得不使用或制作某种多线程事件排队系统,正如其他一些答案中所建议的那样。

答案 3 :(得分:5)

C ++没有内置的事件支持。您必须实现某种线程安全的任务队列。您的主消息处理线程将不断从该队列中获取项目并处理它们。

一个很好的例子是驱动Windows应用程序的标准Win32消息泵:

 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
 {
   MSG msg;
   while(GetMessage(&msg, NULL, 0, 0) > 0)
   {
     TranslateMessage(&msg);
     DispatchMessage(&msg);
   }
   return msg.wParam;
 }

其他线程可以Post向窗口发送消息,然后由该线程处理。

这使用C而不是C ++,但它说明了这种方法。