Event / Task Queue Multithreading C++

前端 未结 8 1096
梦如初夏
梦如初夏 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 15:54

    You can solve this by using Boost's Thread -library. Something like this (half-pseudo):

    
    class GThreadObject
    {
            ...
    
            public:
                    GThreadObject()
                    : _done(false)
                    , _newJob(false)
                    , _thread(boost::bind(>hreadObject::workerThread, this))
                    {
                    }
    
                    ~GThreadObject()
                    {
                            _done = true;
    
                            _thread.join();
                    }
    
                    void functionOne(char *argOne, int argTwo)
                    {
                            ...
    
                            _jobQueue.push(myEvent);
    
                            {
                                    boost::lock_guard l(_mutex);
    
                                    _newJob = true;
                            }
    
                            _cond.notify_one();
                    }
    
            private:
                    void workerThread()
                    {
                            while (!_done) {
                                    boost::unique_lock l(_mutex);
    
                                    while (!_newJob) {
                                            cond.wait(l);
                                    }
    
                                    Event *receivedEvent = _jobQueue.front();
    
                                    ...
                            }
                    }
    
            private:
                    volatile bool             _done;
                    volatile bool             _newJob;
                    boost::thread             _thread;
                    boost::mutex              _mutex;
                    boost::condition_variable _cond;
                    std::queue        _jobQueue;
    };
    

    Also, please note how RAII allow us to get this code smaller and better to manage.

提交回复
热议问题