日期:2014-05-16  浏览次数:20531 次

成员函数 作为 线程函数。测了一天,求解!
本帖最后由 shouso888 于 2013-11-07 23:16:24 编辑
class SomeClass
{
    public:
        SomeClass(int static_data, int none_static_data);
        void TackNoneStaticThreadFunc();

    private:
        void* NoneStaticThreadFunc(void* param);

    private:
        int none_static_data_;
        static int static_data_;
};

TackNoneStaticThreadFunc 会开启线程调用 NoneStaticThreadFunc 作为线程函数,...

线程 Linux C++ 线程函数

------解决方案--------------------
pthread_create的func只能传入一个参数,
成员函数又必须得绑定一个对象才能调用,成员函数编译后第一个参数是this(隐含的)
------解决方案--------------------
/*
 * filename: test.cpp
 */

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

class task
{
public:
  explicit task(int times) : echo_times_(times)
  {
  }

  void active_thread()
  {
    pthread_t tid;
    ::pthread_create(&tid, NULL, task::thread_func, this);
    ::pthread_join(tid, NULL);
  }

private:
  static void* thread_func(void *param)
  {
    task *self = (task*)param;
    for (int i = 0; i < self->echo_times_; ++i)
      std::cout << "echo times: " << i + 1 << std::endl;

    return NULL;
  }
private:
  int echo_times_;
};

int main()
{
  task(5).active_thread();
  return 0;
}


g++ test.cpp -lpthread


[coderchen@self thread]$ ./a.out
echo times: 1
echo times: 2
echo times: 3
echo times: 4
echo times: 5