我正在尝试在我的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*)>'
还有更多…
如何初始化堆栈?
使用C#下载Windows更新
旧的Windows XP上的CRegKey崩溃
一旦我在Active Directory中获得用户组,就如何获得组的SID?
我正在编译:
g++ -std=c++0x C.cpp
编译器版本:
$g++ --version g++ (GCC) 4.7.0 20120507 (Red Hat 4.7.0-5)
我究竟做错了什么?
如何以编程方式读取Windows操作系统中的sqlite数据库的内容?
C ++在Windows中发送一个简单的信号
监视窗口的创build(HWND)
LNK2019:无法parsing的外部符号_main在函数___tmainCRTStartup中引用
std::thread与POSIX线程不是一回事,它不需要void*参数并返回一个void* 。 只要你指定了正确的参数, thread构造函数就可以采取任何可调用的方式。
在这种情况下的具体错误是,你试图启动一个线程,有效地调用c.code() (技术上INVOKE(&C::code,&c) ),但是这是一个无效的调用,因为C::code只有一个参数而你正试图用零来调用它。 只需修改code()上的签名以匹配您所调用的内容即可:
void code() { std::cout << "Code thread executing " << std::endl; }
或者,你可以提供void* arg给thread构造函数:
std::thread t ( &C::code,&c,nullptr ); ^^^^^^^
无论哪种方式,确保你用-pthread编译。
使用operator()使您的类C成为可调用的对象
#include <iostream> #include <thread> class C { public: void operator()( void ) { std::cout << "Code thread executing " << std::endl; return NULL; } }; int main() { C c; std::thread t (c ); t.join(); }
#include <iostream> #include <thread> #include <functional> class C { public: void * code( void) { std::cout << "Code thread executing " << std::endl; return NULL; } }; int main() { C c; std::thread t (std::bind( &C::code,&c )); t.join(); }
并切换到 – std = c ++ 11