c++ - 使用 pthread_create 时出错

标签 c++

<分区>

Possible Duplicate:
pthread Function from a Class

我是 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()
{
 .....
}


}

但我得到了这个错误:

正在初始化“int pthread_create(pthread_t*, const pthread_attr_t*, void* ()(void), void*)”的参数 3 [-fpermissive]

最佳答案

如果您想继续使用 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 thread library .它是一个使用模板的更简单的 RAII 接口(interface),因此您可以将任何函数传递给线程,包括类成员函数(参见 this thread)。

然后,上面的例子简化为:

#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* 之间的强制转换。

关于c++ - 使用 pthread_create 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13128461/

相关文章:

c++ - 取消引用指针以获取值或创建本地对象并以这种方式访问​​值更好吗?

c++ - 为什么比较 long long 和 int 会溢出

c++ - 仅当某个函数后跟另一个函数时才允许调用它

c++ - 特化返回 void 且没有参数的成员函数

c++ - int main() 是否需要在 C++ 上声明?

c++ - 内部编译器错误(CL版本:14.27.29110)

c++ - 在 CallGraphSCCPass 中使用 DominatorTreeWrapperPass

c++ - 以下程序的一些说明

c++ - CMake、链接目录和多个 Boost 安装

c++ - 创建应用程序可以编辑但用户不能编辑的文件