【问题标题】:Call member function of an object using pthread使用 pthread 调用对象的成员函数
【发布时间】:2015-06-30 07:28:21
【问题描述】:

如何使用 pthread 将 thread_ready_function 调用到评论中的线程中?我需要用类对象调用它(在现实世界中,该函数使用先前设置的属性)。

MWE

#include <iostream>
#include <pthread.h>


class ClassA
 {
public:

     void * thread_ready_function(void *arg)
     {
         std::cout<<"From the thread"<<std::endl;

         pthread_exit((void*)NULL);
     }
 };

 class ClassB
 {
     ClassA *my_A_object;
public:
     void test(){
         my_A_object = new ClassA();

         my_A_object->thread_ready_function(NULL);

         // my_A_object->thread_ready_function(NULL);
         //  ^
         //  I want to make that call into a thread.

         /* Thread */
/*
         pthread_t th;
         void * th_rtn_val;

         pthread_create(&th, NULL, my_A_object.thread_ready_function, NULL);
         pthread_join(th, &th_rtn_val);
*/
     }
 };

int main()
{
    ClassB *my_B_object = new ClassB();
    my_B_object->test();

    return 0;
}

【问题讨论】:

  • 可以用c++11线程吗?
  • 我会看看 c++ 11。但我认为它的支持很棘手,我想知道是否有办法使用 pthread
  • pthread Function from a Class 的可能重复项

标签: c++ pthreads


【解决方案1】:

如果你不想使用C++11或者stl或者boost,你的成员函数必须使用static关键字,这样pthread才能调用你的成员函数! 示例代码:

#include <iostream>
#include <pthread.h>

using namespace std;

class A{
  public:
    static void* thread(void* args);
    int parella_thread(int thread_num);
};

void* A::thread(void* args)
{
  cout<<"hello world"<<endl;
}

int A::parella_thread(int thread_num)
{
  pthread_t* thread_ids = new pthread_t[thread_num];
  for(int i=0;i<thread_num;i++)
  {
    pthread_create(&thread_ids[i],NULL,thread,(void*)NULL);
  }
  delete[] thread_ids;
}

int main(int argc,char*argv[])
{
  A test;
  test.parella_thread(4);
  return 0; 
}

【讨论】:

    猜你喜欢
    • 2012-01-02
    • 1970-01-01
    • 1970-01-01
    • 2015-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多