【问题标题】:pthread run function private in classpthread 在类中运行私有函数
【发布时间】:2013-03-01 10:37:59
【问题描述】:

我正在编写一个包含 pthread 的类,它的头文件和 .cpp 定义文件。

在 .h 中我有:

class test
{
    public:
        int a;
    ...
    private:
        typedef void (*myfunc)(void *p);
        static myfunc pthreadRun;
}

在 .cpp 我有:

...
typedef void (*myfunc)(void *p);
myfunc test::pthreadRun
{
    this->a = 10;
    pthread_exit(NULL);
}
...

我收到一个错误:void (* test::pthreadRun)(void*) 不是class test 的静态成员,还有一堆其他错误,但这是第一个。

我很困惑,因为它被声明为静态:/

pthreadRunpthread_create()的线程运行函数

我错过了什么?

【问题讨论】:

  • here。您不能为此使用私有方法。至少不是这样……
  • 你不能用 typedef 声明一个函数。

标签: c++ class pthreads header-files static-members


【解决方案1】:

很难准确猜出您要做什么,但首先我想我会像这样重写您的代码:

class test
{
    public:
        int a;
    ...
    private:
        static void pthreadRun(void *p);
}

void test::pthreadRun(void *p)
{
    // this->a = 10; This line is now a big problem for you.
    pthread_exit(NULL);
}

所以这是您正在寻找的那种结构,尽管您无法从此上下文中访问成员元素(例如 this->a),因为它是一个静态函数。

通常处理这个问题的方法是使用 this 指针启动线程,以便在函数中:

void test::pthreadRun(void *p)
{
     test thistest=(test)p;
     thistest->a=10;  //what you wanted
     thistest->pthreadRun_memberfunction(); //a wrapped function that can be a member function
    pthread_exit(NULL);
}

您应该能够将所有这些函数设为私有/受保护(假设您从此类中启动线程,我认为这样做可能更可取。

【讨论】:

    猜你喜欢
    • 2012-03-25
    • 2010-11-12
    • 1970-01-01
    • 2016-04-22
    • 1970-01-01
    • 1970-01-01
    • 2017-02-20
    • 2013-12-17
    相关资源
    最近更新 更多