C++ PTHREAD 错误:非静态成员函数的使用无效

c++ pthread error: invalid use of non-static member function

本文关键字:无效 函数 静态成员 PTHREAD 错误 C++      更新时间:2023-10-16

我有错误:当我尝试编译以下代码时,非静态成员函数的使用无效:

int main()
{
    data d;
    cta ce;
    pthread_t thread1;
    pthread_t thread2;
    pthread_create( &thread1, NULL, d.subscribe, NULL ); 
    pthread_create( &thread2, NULL, ce.startStrategy, NULL ); 
    pthread_join(thread1,NULL);
    pthread_join(thread2,NULL);
    return 0;
}
// cta.cpp
// ...
static void* cta::startStrategy()
{
    std::cout<<"haha"<<std::endl;
}
// data.cpp
// ...
static void* data::subscribe()
{ 
  std::cout<<"haha"<<std::endl;
}

收到错误:

main.cpp:38:52: error: invalid use of non-static member function
pthread_create( &thread1, NULL, d.subscribe, NULL ); 
                                                ^
main.cpp:39:60: error: invalid use of non-static member function
pthread_create( &thread2, NULL, ce.startStrategy, NULL ); 

但是,类似的代码片段效果很好:

#include <iostream>
#include <pthread.h>
  class Foo {
    public:
      static void func() {
        std::cout << "hi" << std::endl;
      }
  };
  int main() {
    Foo ins;
    pthread_t pt;
    pthread_t pt1;
    pthread_create( &pt, NULL, ins.func, NULL );
    pthread_create( &pt1, NULL, ins.func, NULL );
    pthread_join(pt, NULL);
    pthread_join(pt1, NULL);
    return 0;
  }

它编译得很好并打印了两次"嗨",我想知道我的代码可能出了什么问题,因为我已经从 void 更改为静态 void 并遵循相同的模式,为什么我仍然得到非静态错误?

首先,不要使用 pthread 。 用C++ std::thread,成就幸福。

见证这一点:

std::thread t1(&data::subscribe, &d);
std::thread t2(&cta::start_strategy, &ce);

其次,问题最可能的原因是static修饰符应该在类定义(.h 文件(中使用,而不是在类外的函数定义中使用。

如果你要使用pthread_create,你必须向它传递它想要的参数。启动例程是 void *(*start_routine) (void *) 。请注意,其中没有任何关于任何成员函数的内容,无论是static还是其他。因此,即使代码碰巧在某些平台上工作,代码也是不正确的。