动态提升线程运行存储在具有共享指针的向量中的对象的方法

时间:2014-12-16 18:13:26

标签: c++ multithreading boost

我有一个相机类,它是网络摄像机的抽象。该类有一个方法rxImageThread(),它本质上是一个图像服务器。我想在n个线程中为n个摄像机运行n个服务器,其中n是动态设置的(来自配置文件)。

相机对象存储在矢量中:

std::vector<boost::shared_ptr<camera> > cameras;

我在循环中创建相机对象:

cameras.push_back( boost::shared_ptr<camera> (new camera(ip, controlPort, dataPort, imagePort, name)) );

我有一个存储线程的向量:

std::vector<boost::shared_ptr<boost::thread> > threads;

在一个循环中,我想让每个摄像头的rxImageThread()在一个线程中运行:

for(int i = 0;i<cameras.size();i++){
   threads.push_back( boost::shared_ptr<boost::thread> (new boost::thread(&camera::rxImageThread, &cameras[i]) );
   cameras[i]->startRx();
}

然而,我得到了一个错误:

‘void (camera::)()’ incompatible with object type ‘boost::shared_ptr<camera>’

这表明我应该使用类似的代码:

threads.push_back( boost::shared_ptr<boost::thread> (new boost::thread(std::mem_fn(&camera::rxImageThread),&cameras[i]  ));

然而,这会产生同样的错误。

我有点迷失在这里发生了什么,更不用说如何解决它了。

1 个答案:

答案 0 :(得分:2)

shared_ptr<>不是地址。你必须在它上面调用.get()来获取对象地址。

如:

threads.push_back( boost::shared_ptr<boost::thread> (new boost::thread(&camera::rxImageThread, cameras[i].get()) );

除了解决这个问题之外,我想知道拥有一个拥有摄像头并控制线程生命周期的控制器类是否更清晰。这样,您可以保证在拥有线程终止之前不删除相机。

编辑:

这是一个展示这个想法的完整程序。线程安全启动和停止摄像头。没有内存泄漏或线程超出相机的可能性:

#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>

#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;


namespace {
    boost::mutex _cout_mutex;
}
// a cut-down camera class

struct camera
{
    camera(std::string hostname, unsigned short port)
    : _hostname(hostname)
    , _port(port)
    {}

    std::string description() const {
        std::ostringstream ss;
        ss << _hostname << ':' << _port;
        return ss.str();
    }

    std::string _hostname;
    unsigned short _port;
};



struct camera_controller
{
    camera_controller(const std::string& hostname, unsigned short port)
    : _camera(hostname, port)
    , _stop(false)
    {}

    void start() {
        boost::unique_lock<boost::mutex> outlock(_cout_mutex);
        cout << "starting " << _camera.description() << endl;
        outlock.unlock();

        assert(!_thread_ptr);
        _stop = false;
        _thread_ptr.reset(new boost::thread(boost::bind(&camera_controller::camera_thread, this)));
    }

    void stop() {
        if (_thread_ptr) {
            boost::unique_lock<boost::mutex> outlock(_cout_mutex);
            cout << "stopping " << _camera.description() << endl;
            outlock.unlock();

            notify_stop();
            _thread_ptr->join();
            _thread_ptr.reset();
        }
    }

    ~camera_controller()
    {
        stop();
    }

private:

    void camera_thread()
    {
        while (!time_to_stop())
        {
            // do things with the camera
            boost::unique_lock<boost::mutex> outlock(_cout_mutex);
            cout << "working: " << _camera.description() << endl;
            outlock.unlock();
            boost::this_thread::sleep_for(boost::chrono::milliseconds(1000));

        }
        boost::unique_lock<boost::mutex> outlock(_cout_mutex);
        cout << "shutting down: " << _camera.description() << endl;
        outlock.unlock();
    }

    void notify_stop() {
        boost::unique_lock<boost::mutex> outlock(_cout_mutex);
        cout << "notify stop for " << _camera.description() << endl;
        outlock.unlock();
        _stop = true;
        // would normally signal a condition variable here
    }

    bool time_to_stop() const {
        // test the stop condition
        return _stop;
    }

private:
    camera _camera;
    boost::shared_ptr<boost::thread> _thread_ptr;

    // this could be a condition variable in a real application
    bool _stop;
};


struct application
{
    typedef boost::shared_ptr<camera_controller> control_ptr;

    control_ptr add_camera(const std::string& host, unsigned short port)
    {
        control_ptr p(new camera_controller(host, port));
        p->start();

        // tightest lock possible on shared resources
        boost::unique_lock<boost::mutex> lock(_cameras_mutex);
        _camera_controllers.push_back(p);
        return p;
    }

    // for example...
    void destroy_camera_by_index(size_t i)
    {
        boost::unique_lock<boost::mutex> lock(_cameras_mutex);
        control_ptr cam_ptr = _camera_controllers[i];
        _camera_controllers.erase(_camera_controllers.begin() + i);
        lock.unlock();

        // note - this blocks until the camera thread is stopped
        cam_ptr->stop();
    }

    size_t camera_count() const {
        boost::unique_lock<boost::mutex> lock(_cameras_mutex);
        return _camera_controllers.size();
    }


private:

    std::vector<control_ptr> _camera_controllers;
    mutable boost::mutex _cameras_mutex;
};

int main()
{
    application app;
    app.add_camera("camera_a", 0);
    app.add_camera("camera_b", 1);
    app.add_camera("camera_c", 2);
    app.add_camera("camera_d", 3);
    app.add_camera("camera_e", 4);

    while(app.camera_count() > 2) {
        boost::this_thread::sleep_for(boost::chrono::seconds(2));
        size_t i = rand() % app.camera_count();
        app.destroy_camera_by_index(i);
    }

    boost::this_thread::sleep_for(boost::chrono::seconds(2));

}