使用pthread_create时出错

Getting error when using pthread_create

本文关键字:出错 create pthread 使用      更新时间:2023-10-16

可能的重复:
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 );

如果你声明函数静态,它将编译。