gpt4 book ai didi

c++ - 编译 C++ 线程

转载 作者:IT王子 更新时间:2023-10-29 00:25:24 26 4
gpt4 key购买 nike

我正在尝试在我的 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*。只要您指定了正确的参数,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 进行编译。

关于c++ - 编译 C++ 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31012096/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com