其他分享
首页 > 其他分享> > c – 如何阻止std / boost :: thread复制我的对象而不是传递引用?

c – 如何阻止std / boost :: thread复制我的对象而不是传递引用?

作者:互联网

从这个示例项目的输出中,我看到我的对象的三个副本在我只期望一个时创建.并且只想要一个.我该怎么解决这个问题?

在我的真实代码中,ThreadedThing是一个更大/更重的类,它位于一个线程池中,我宁愿只有我真正需要的那么多.但我写了一个小演示应用程序(下面)来演示这种行为.我从增强线程样本中复制了基本代码,所以我希望它能够正常工作,所以我担心这是一个C新手的问题.

我之前编写过多线程代码,但是在Delphi而不是C中.对于这个代码,valgrind说没有泄漏,这一切都很好,但仍然有三个对象被创建,我宁愿有一个.

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

using namespace std;

class ThreadedThing {
public:
    ThreadedThing() {
        cout << "ThreadedThing created" << endl;
    }
    ThreadedThing(const ThreadedThing &orig) {
        cout << "ThreadedThing copy created" << endl;
    }
    ~ThreadedThing() {
        cout << "ThreadedThing destroyed" << endl;
    }
    void operator()() {
        cout << "ThreadedThing running" << endl;
        sleep(2);
    }
};

int main() {
    std::vector < shared_ptr < boost::thread >> threads;
    cout << "Started" << endl;

    ThreadedThing thing;
    std::shared_ptr<boost::thread> thread(new boost::thread(thing));
    threads.push_back(thread);

    for (std::vector < std::shared_ptr < boost::thread >> ::iterator it = threads.begin(); it != threads.end(); ++it) {
        (*it)->join();
        cout << "joined" << endl;
    }
    cout << "stopped" << endl;
    return 0;
}

/* output
Started
ThreadedThing created
ThreadedThing copy created
ThreadedThing copy created
ThreadedThing destroyed
ThreadedThing running
ThreadedThing destroyed
joined
stopped
ThreadedThing destroyed
*/

解决方法:

只需在C 11中使用std :: ref或在无法访问C 11时使用boost :: ref.

标签:boost-thread,c,c11,multithreading,boost
来源: https://codeday.me/bug/20190825/1718264.html