1

I'm trying to send a vector to parameter of another thread's function :

void foo(){}
const int n = 24;
void Thread_Joiner(std::vector<thread>& t,int threadNumber)
{
    //some code
}
int main()
{
    std::vector<thread> threads(n, thread(foo));
    thread Control_thread1(Thread_Joiner, threads, 0);//error
    thread Control_thread2(Thread_Joiner, threads, 1);//error
    //...
}

The above code give this error :

: attempting to reference a deleted function

I checked the header file of std::thread It seems that copy constructor is deleted : thread(const thread&) = delete;

std::thread have a move constructor but I don't think in this case using move is helpfull because Control_thread1 and Control_thread2 use same vector !

If I use thread **threads;... instead of that vector It works fine but I don't want to use pointers .

What should I do ?!

1 Answer 1

3

std::thread copies the arguments used for the bind. Use std::ref to contain it as a reference:

std::thread Control_thread1(Thread_Joiner, std::ref(threads), 0);
std::thread Control_thread2(Thread_Joiner, std::ref(threads), 1);
Sign up to request clarification or add additional context in comments.

5 Comments

@xyz The constructor of your vector is also attempting to copy a thread(foo) object.
well that's the question how can I fix that ?! using vector<thread*> ?
@xyz Yes, but it's preferable to use smart pointers: std::vector<std::shared_ptr<std::thread>> threads(n, std::make_shared<std::thread>(foo)). And if you're not intending to extend the vector past its declared size, use std::array<24, std::shared_ptr<std::thread>>
@xyz Actually all you need is std::vector<std::thread> threads; for (auto& th : threads) th = std::thread(foo);.
@xyz I know but it was wrong of me to suggest using shared_ptr when it works fine without. See this example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.