2017-05-09 76 views
0

首先是CPP的std ::线程的尝试,我想说的是,我已经就这一主题使用删除功能

Xcode 7: C++ threads ERROR: Attempting to use a deleted function研究,但没有相关的...

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

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

这是我的问题... ...:

铛错误:

/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))...); 

这是我的代码:

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); 

如果有人可以帮助我,会非常有帮助! :)

问候;)

+3

它应该像'std :: ref(ret)',你应该有'bool'通过'thread'或使用'std :: atomic '...... – Jarod42

+0

非常感谢你,它是没有编译的std :: ref(ret)...如果你把它写成答案,我将能够关闭这张票:) –

回答

1

要传递给线程的引用,您必须使用std::reference_wrapper,您可以使用std::ref获取该引用。所以,你的代码就变成了:

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

注: bool ret大概应该是std::atomic<bool> ret,还是应该应该有一个线程bool。否则,您可能同时访问ret

+0

谢谢你很多! :)但它仍然适用于vector :: push_back(); –

+0

我使用了'emplace_back',因为它缩短了行(并避免了一个(消失?)移动)。 – Jarod42

0

删除的功能,它是抱怨是常量线程删除的拷贝构造函数。

被删除的功能的问题,你可以使用:

threads.emplace_back(

相反的:

threads.push_back(

什么评论者还提到的是,该功能是创建多个线程,并传递给他们对同一个布尔返回变量的引用。

如果你不使用atomic_bool,它会崩溃,即使你这样做,他们也会报告回同一个内存位置,如果其中一个返回false,这个函数会丢失通知。

+0

这就是为什么我把它写成第一个参数。我发函数地址为std :: thread。我知道它可以与非静态函数成员 –

+0

一起工作我有我的代码的其他部分,我编译几周前,我确实调用非静态成员函数与std ::线程...我真的不知道为什么不工作...加上它是在同一个文件... –

+0

我试图重命名重载名称前面的下划线,但没有任何改变...我开始认为重新启动大声笑 –