Event / Task Queue Multithreading C++

前端 未结 8 1104
梦如初夏
梦如初夏 2021-02-04 15:18

I would like to create a class whose methods can be called from multiple threads. but instead of executing the method in the thread from which it was called, it should perform t

8条回答
  •  情歌与酒
    2021-02-04 16:01

    Here's a class I wrote for a similar purpose (I use it for event handling but you could of course rename it to ActionQueue -- and rename its methods).

    You use it like this:

    With function you want to call: void foo (const int x, const int y) { /*...*/ }

    And: EventQueue q;

    q.AddEvent (boost::bind (foo, 10, 20));

    In the worker thread

    q.PlayOutEvents ();

    Note: It should be fairly easy to add code to block on condition to avoid using up CPU cycles.

    The code (Visual Studio 2003 with boost 1.34.1):

    #pragma once
    
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    using std::string;
    
    
    // Records & plays out actions (closures) in a safe-thread manner.
    
    class EventQueue
    {
        typedef boost::function  Event;
    
    public:
    
        const bool PlayOutEvents ()
        {
            // The copy is there to ensure there are no deadlocks.
            const std::vector eventsCopy = PopEvents ();
    
            BOOST_FOREACH (const Event& e, eventsCopy)
            {
                e ();
                Sleep (0);
            }
    
            return eventsCopy.size () > 0;
        }
    
        void AddEvent (const Event& event)
        {
            Mutex::scoped_lock lock (myMutex);
    
            myEvents.push_back (event);
        }
    
    protected:
    
        const std::vector PopEvents ()
        {
            Mutex::scoped_lock lock (myMutex);
    
            const std::vector eventsCopy = myEvents;
            myEvents.clear ();
    
            return eventsCopy;
        }
    
    private:
    
        typedef boost::recursive_mutex Mutex;
        Mutex myMutex;
    
        std::vector  myEvents;
    
    };
    

    I hope this helps. :)

    Martin Bilski

提交回复
热议问题