使用pthread_create时出错
Getting error when using pthread_create
可能的重复:
pthread 类函数
我对 c++ 相当陌生,我正在做一个关于 TCP 的项目。
我需要创建一个线程,所以我用谷歌搜索并找到了这个。 http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html
我遵循它的语法,但遇到错误: 类型为"void* (ns3::TcpSocketBase::)()"的参数与"void* ()(void)"不匹配
代码:
tcp-socket-base.h:
class TcpSocketBase : public TcpSocket
{
public:
...
void *threadfunction();
....
}
tcp-socket-base.cc:
void
*TcpSocketBase::threadfunction()
{
//do something
}
..//the thread was create and the function is called here
pthread_t t1;
int temp = pthread_create(&t1, NULL, ReceivedSpecialAck, NULL); //The error happens here
return;
...
任何帮助将不胜感激。谢谢!
编辑:
我接受了建议,使线程函数成为非成员函数。
namespaceXXX{
void *threadfunction()
int result = pthread_create(&t1, NULL, threadfunction, NULL);
NS_LOG_LOGIC ("TcpSocketBase " << this << " Create Thread returned result: " << result );
void *threadfunction()
{
.....
}
}
但是我得到了这个错误:
初始化参数 3 的 'int pthread_create(pthread_t*, const pthread_attr_t*, void* ()(void),void*)' [-fallowive]
如果你想继续使用 pthreads,一个简单的例子是:
#include <cstdio>
#include <string>
#include <iostream>
#include <pthread.h>
void* print(void* data)
{
std::cout << *((std::string*)data) << "n";
return NULL; // We could return data here if we wanted to
}
int main()
{
std::string message = "Hello, pthreads!";
pthread_t threadHandle;
pthread_create(&threadHandle, NULL, &print, &message);
// Wait for the thread to finish, then exit
pthread_join(threadHandle, NULL);
return 0;
}
如果可以的话,更好的选择是使用新的 C++11 线程库。这是一个更简单的 RAII 接口,它使用模板,以便您可以将任何函数传递给线程,包括类成员函数(请参阅此线程)。
然后,上面的示例简化为:
#include <cstdio>
#include <string>
#include <iostream>
#include <thread>
void print(std::string message)
{
std::cout << message << "n";
}
int main()
{
std::string message = "Hello, C++11 threads!";
std::thread t(&print, message);
t.join();
return 0;
}
请注意如何直接传入数据 - 不需要在void*
之间传递转换。
您希望将类的成员函数传递给pthread_create
函数。线程函数应该是具有以下签名的非成员函数
void *thread_function( void *ptr );
如果你声明函数静态,它将编译。
相关文章:
- 访问者访问变体并返回不同类型时出错
- 在Linux for Windows上编译C++代码时出错
- 读取文件的最后一行并输入到链接列表时出错
- 重载操作程序时出错>>用于类中的字符串 memebr
- 调用专用模板时出错"no matching function for call to [...]"
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- LINK 尝试使用 OpenSSL evp aes 256 c++ 时出错
- 在Google Kick start中提交时出错
- 在c++中访问int到类对象的映射时出错
- 分段错误当我试图运行程序时出错
- 使用dynamic_cast和构造函数时出错
- CHECK(调用)函数在Google Colab中出错
- 用pybind11包装C++抽象类时出错
- 为x86而非x64编译时出错
- 从R调用C++函数并对其进行集成时出错
- 这个函数哪里出错了
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 为重写std::exception的库生成swig接口时出错
- 导入/导出变量时出错
- PrintWindow函数在notepad.exe中出错