C++,linux,如何将非静态方法从单例传递给 pthread_create?

标签 c++ linux multithreading g++ pthreads

我在从单例类线程化非静态方法时遇到问题,请查看代码:

//g++ main.cc -lpthread
#include<iostream>
#include<unistd.h>                 
#include<pthread.h>

class SLAYER{
  private:
    SLAYER(){};
    ~SLAYER(){};
    static SLAYER *singleton;
    pthread_t t1, t2;

  public: 
    static void *born(){
      singleton = new SLAYER;
    };
    static void *death(){
      delete singleton;
      singleton = NULL;
    };
    static void *start(){
      pthread_create(&singleton->t1,NULL,singleton->KerryRayKing, NULL);
      pthread_create(&singleton->t2,NULL,singleton->JeffHanneman, NULL);
    };
    void *JeffHanneman(void *arg){
      sleep(1);
      std::cout << "(1964-2013) R.I.P.\n";
      (void) arg;
      pthread_exit(NULL);
    };
    static void *KerryRayKing(void *arg){
      sleep(1);
      std::cout << "(1964-still with us) bald\n";
      (void) arg;
      pthread_exit(NULL);
    };
};

SLAYER *SLAYER::singleton=NULL;

int main(){
  SLAYER::born();
  SLAYER::start();
  std::cout << "thread started\n";
  sleep(5);
  SLAYER::death();
  return 0;
}

如您所见,KerryRayKing()JeffHanneman() 不同,它是静态的。我未能将 JeffHanneman() 传递给 pthread_create(),在编译时我得到:

cannot convert ‘SLAYER::JeffHanneman’ from type ‘void* (SLAYER::)(void*)’ to type ‘void* (*)(void*)’

我尝试了几次转换,但都失败了...在这个 cas 中不可能使用非静态方法吗?

编辑:

我忘了说,我不想允许从外部访问 JeffHanneman()

最佳答案

简短的回答:你不能那样做。

有几种解决方法,最简单的是使用 static 包装函数,例如

static void *JHWrapper(void *self)
{
   SLAYER *that = static_cast<SLAYER*>(self);
   return that->JeffHanneman(); 
}

void *JeffHanneman(){   // Note "arg" removed.
  sleep(1);
  std::cout << "(1964-2013) R.I.P.\n";
  pthread_exit(NULL);
};

现在,pthread 创建变成:

 pthread_create(&singleton->t1,NULL, SLAYER::JHWrapper, static_cast<void *>(singleton));

[我避免使用“JHRapper”的双关语,因为我认为那会相当贬低...]

关于C++,linux,如何将非静态方法从单例传递给 pthread_create?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17136885/

相关文章:

python - 从 std::vector<double> 到 Python 列表的转换失败( boost python)

c++ - 如何使用 C++ 返回一个抽象类

c++ - 如何强制函数参数为同一类型并且不允许使用类型构造函数来匹配给定类型?

linux - shell脚本不运行其中的其他脚本

linux - 有谁知道如何在 Visual Studio Code 中重置 gitlens 扩展的身份验证

Java,Threads,只会将 run() block 作为线程的一部分,还是作为 start() 调用后的代码的一部分?

c# - 静态类的竞争条件?

c++ - 有效地使用多个分配器

仅使用 AH 的 Linux IPSec 传输模式

java - 理解死锁、同步