Rodolphe Chartier
Rodolphe Chartier

Reputation: 66

CPP std::thread attempt to use a deleted function

First of all, I want to say that i already made researches on the subject, but nothing relevant...

(Error creating std::thread on Mac OS X with clang: "attempt to use a deleted function")

(Xcode 7: C++ threads ERROR: Attempting to use a deleted function)

(xcode - "attempt to use a deleted function" - what does that mean?)

And here's my issue...:

clang error:

/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/thread:347:5: error: attempt to use a deleted function
__invoke(_VSTD::move(_VSTD::get<0>(__t)), _VSTD::move(_VSTD::get<_Indices>(__t))...);

And that's my code:

bool GenAI::loadAIs()
{
    bool ret = true;

    if (_nbThread > 1)
    {
        std::vector<std::thread> threads;

        for (unsigned int i = 0; i < _nbThread; ++i)
            threads.push_back(std::thread(static_cast<void (GenAI::*)(bool &, unsigned int)>(&GenAI::loadAIs), this, ret, i));
        for (unsigned int i = 0; i < _nbThread; ++i)
            threads[i].join();
    }
    else
        loadAIs(ret, 0);
    return ret;
}

// And the prototype of the function that i try to call
void GenAI::loadAIs(bool & ret, unsigned int iThread);

If some one could help me that'd be really helpful ! :)

Regards ;)

Upvotes: 1

Views: 4348

Answers (3)

Vladimir Mikov
Vladimir Mikov

Reputation: 1

I would get back to reading. Just use another language - Python!

Or use emplace_back

Vladimir Mikov 4044087744

Upvotes: -1

Jarod42
Jarod42

Reputation: 217085

To pass reference to thread, you have to use std::reference_wrapper, that you can obtain with std::ref. So your code becomes:

threads.emplace_back(static_cast<void (GenAI::*)(bool &, unsigned int)>(&GenAI::loadAIs),
                     this,
                     std::ref(ret),
                     i));

Note: bool ret should probably be std::atomic<bool> ret, or should should have one bool by thread. Else you may have concurrent access on ret.

Upvotes: 3

didiz
didiz

Reputation: 1099

The deleted function that it is complaining about is a deleted copy constructor for const thread.

For the deleted function problem, you can use:

threads.emplace_back(

Instead of:

threads.push_back(

What the commenter also referred to is that the function is creating more than one thread and passing to them a reference to the same boolean return variable.

It will crash if you don't use atomic_bool and even if you do, they will all report back to the same memory location, making the function miss the notification if one of them returns false.

Upvotes: 0

Related Questions