编译C线程

我正在尝试在我的C应用程序上使用线程.

我的代码是:

#include <iostream>
#include <thread>

class C
{
public:

    void * code( void * param )
    {
        std::cout << "Code thread executing " << std::endl;
        return NULL;
    }
};

int main()
{
    C c;
    std::thread t ( &C::code,&c );
    t.join();
}

编译时,我得到了这些错误

In file included from /opt/centos/devtoolset-1.0/root/usr/lib/gcc/x86_64-redhat-linux/4.7.0/../../../../include/c++/4.7.0/bits/move.h:57:0,from /opt/centos/devtoolset-1.0/root/usr/lib/gcc/x86_64-redhat-linux/4.7.0/../../../../include/c++/4.7.0/bits/stl_pair.h:61,from /opt/centos/devtoolset-1.0/root/usr/lib/gcc/x86_64-redhat-linux/4.7.0/../../../../include/c++/4.7.0/bits/stl_algobase.h:65,from /opt/centos/devtoolset-1.0/root/usr/lib/gcc/x86_64-redhat-linux/4.7.0/../../../../include/c++/4.7.0/bits/char_traits.h:41,from /opt/centos/devtoolset-1.0/root/usr/lib/gcc/x86_64-redhat-linux/4.7.0/../../../../include/c++/4.7.0/ios:41,from /opt/centos/devtoolset-1.0/root/usr/lib/gcc/x86_64-redhat-linux/4.7.0/../../../../include/c++/4.7.0/ostream:40,from /opt/centos/devtoolset-1.0/root/usr/lib/gcc/x86_64-redhat-linux/4.7.0/../../../../include/c++/4.7.0/iostream:40,from C.cpp:1:
/opt/centos/devtoolset-1.0/root/usr/lib/gcc/x86_64-redhat-linux/4.7.0/../../../../include/c++/4.7.0/type_traits: In instantiation of 'struct std::_Result_of_impl<false,false,std::_Mem_fn<void* (C::*)(void*)const>,C*>':
/opt/centos/devtoolset-1.0/root/usr/lib/gcc/x86_64-redhat-linux/4.7.0/../../../../include/c++/4.7.0/type_traits:1857:12:   required from 'class std::result_of<std::_Mem_fn<void* (C::*)(void*)const>(C*)>'

还有更多……

我正在编译:

g++ -std=c++0x  C.cpp

编译器版本:

$g++ --version
g++ (GCC) 4.7.0 20120507 (Red Hat 4.7.0-5)

我究竟做错了什么?

解决方法

std :: thread与POSIX线程不同,它不必采用void *参数并返回void *.只要指定了正确的参数,线程构造函数就可以使用任何可调用的.

这种情况下的具体错误是你试图启动一个有效调用c.code()的线程(技术上是INVOKE(& C :: code,& c)),但这是一个无效的调用,因为C ::代码接受一个参数,你试图用零调用它.只需在代码()上修复签名即可与您调用内容相匹配:

void code()
{
    std::cout << "Code thread executing " << std::endl;
}

或者,您可以向线程构造函数提供void * arg:

std::thread t ( &C::code,&c,nullptr );
                              ^^^^^^^

无论哪种方式,请确保使用-pthread进行编译.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...