c++ - 动态 boost 线程运行存储在具有共享指针的 vector 中的对象的方法

标签 c++ multithreading boost

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

相机对象存储在一个 vector 中:

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

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

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

我有一个 vector 来存储线程:

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]  ));

但是,这会得到相同的错误。

我对这里发生的事情有点迷茫,更不用说如何解决了。

最佳答案

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

例如:

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

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

编辑:

这里有一个完整的程序来演示这个想法。线程安全地启动和停止相机。没有内存泄漏或线程生命周期超过相机的可能性:

#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));

}

关于c++ - 动态 boost 线程运行存储在具有共享指针的 vector 中的对象的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27511223/

相关文章:

java - Java 中的 Thread.sleep() 有多昂贵?

boost::shared_ptr 的 C++ vector

c++ - 具有未知参数 vector 类型的虚函数

c++ - std::cin 到 char 数组会跳过空格吗?

c++ - 'std::thread' 如何确定传递给构造函数的可变参数的数量

java - Android - 服务如何在 Activity 关闭后继续运行?

c++ - boost asio 什么时候调用 async_read_some 回调?

c++ - boost 哈纳 : create a map from a set and a default value

C++ 基于文本的 RPG 库存系统

c++ - 类解决方法的虚拟模板成员