簡體   English   中英

如何停止std / boost :: thread復制我的對象而不是傳遞引用?

[英]How do I stop std/boost::thread copying my object rather than passing references?

從這個示例項目的輸出中,我看到我的對象的三個副本在我只期望一個時創建。 並且只想要一個。 我該怎么解決這個問題?

在我的真實代碼中,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時,只需在C ++ 11中使用std::ref或使用boost::ref

有充分證據表明, boost::thread的構造函數與std::thread ,不接受引用作為參數。 要解決此問題,您可以編寫一個包含引用的小shell對象,並在復制時保留它。

我就是這樣做的:

/* container to allow passing an object reference to std::thread()
 * without this std::thread() would run on a copy
 */
template<typename T>
struct holder {
    holder(T& payload) : payload(payload) {}
    void operator()() { payload(); }

    T& payload;
};

然后像這樣使用它:

BackgroundTaskQueue queue;

// start worker thread
holder<BackgroundTaskQueue> h(queue);
queuethread = new std::thread(h);
// h is not needed anymore

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM