jeudi 21 mai 2015

Why does having a reference type in thread arguments cause compile error when `emplace`ing in a `thread` vector?

Sorry if the question was not well worded enough, but that's the best I could rephrase my question as concisely as possible.

The situation I am talking about is this:

#include <thread>
#include <vector>
#include <iostream>

using namespace std;

void do_work(vector<string> &foo)
{
    foo.emplace_back("hi");
    cout << "hi" << endl;
}

int main()
{
    vector<thread> threads;
    vector<string> ds;

    for (int i = 0; i < 10; ++i)
        threads.emplace_back(do_work, ds);

    for (auto it = threads.begin(); it != threads.end(); ++it)
        it->join();
}

do_work is all threads' entrance point, which accepts a reference to vector<string> object and creates a new string object at the end. If I create 10 of these and all vector<string> objects that have been passed on to the worker threads are the same object, then, in the end, I should get 10 "hi" strings in the vector. However, the code doesn't seem to compile in g++. It will complain about some type named type in thread missing, but essentially using the reference type as argument must have broken a template or two. In order to circumvent the problem, I could modify do_work function to explicitly accept the pointer to the vector object, or I could create another vector object that resides outside the function scope, so that all routines could access the object (it can get messy). Here is one example.

#include <thread>
#include <vector>
#include <iostream>

using namespace std;

vector<string> foo;

void do_work()
{
    foo.emplace_back("hi");
    cout << "hi" << endl;
}

int main()
{
    vector<thread> threads;

    for (int i = 0; i < 10; ++i)
        threads.emplace_back(do_work);

    for (auto it = threads.begin(); it != threads.end(); ++it)
        it->join();
}

So my question is why doesn't c++ allow such type declarations? It seems arbitrary that such intuitive and logical feature is apparently "unsupported" by the g++ compiler.

P.S. and yes, I have searched google for an answer, but I might have missed a specific keyword that describes this phenomenon, which I am not aware of, so show some mercy if you think this is a very basic concept and I should have googled it first etc.

Aucun commentaire:

Enregistrer un commentaire