在C ++中使用pthreads中的参数传递成员函数

时间:2017-12-11 10:34:56

标签: c++ pthreads

我将一个类成员函数传递给pthread_create并获得低于错误。我知道stackoverflow上已有很多查询,他们说是围绕类成员函数创建一个静态帮助器,并将pthread和函数回调中的静态函数作为pthread_create中的最后一个参数传递,但在我的例子中,成员函数有参数也。所以,我的问题略有不同。 我应该在哪里传递成员函数参数?任何帮助都将受到高度赞赏。

def get_name(data, match):
    result = []  # store for our result
    last_element = None  # store the last non-matching element
    for element in data:  # go through each element
        if match in element:  # if match...
            result.append(last_element)  # add the last non-matching element
        else:
            last_element = element  # set the last non-matching element to the current
            result.append(element)  # add it to the result
    return result  # return the result

data = ['2017','No 1','No 2','2018','No 3','No 4','No 5']
print(get_name(data, "No"))  # ['2017', '2017', '2017', '2018', '2018', '2018', '2018']

错误:

#include <stdio.h>
#include <pthread.h>

struct Point
{
  int y;
  int z;
};

class A
{
  int x;

  public:
    int getX();
    void setX(int val) {x = val;}

    void* func(void* args) 
    {
      Point p = *(Point *)args;

      int y = p.y;
      int z = p.z;

      return (void *)(x + y + z); 
    }


    void myFunc()
    {
      int y = 12;
      int z = 2;

      pthread_t tid;

      Point p;
      p.y = y;
      p.z = z;

      pthread_create(&tid, NULL, func, &p);
      pthread_join(tid, NULL);
    }
};

int main(int argc, char *argv[])
{

  A a;

  a.myFunc();

  return 0;
}

1 个答案:

答案 0 :(得分:0)

问题是你没有将this指针传递给线程create方法。这需要添加到参数列表中。

#include <utility>
#include <pthread.h>

struct Point
{
  int y;
  int z;
};

class A
{
  int x;

  public:
    int getX();
    void setX(int val) {x = val;}

    static void* func(void* args) 
    {
      std::pair< A*, Point > tp = *(std::pair< A*, Point > *)args;

      int y = tp.second.y;
      int z = tp.second.z;

      return (void *)(tp.first->x + y + z); 
    }


    void myFunc()
    {
      int y = 12;
      int z = 2;

      pthread_t tid;

      Point p;
      p.y = y;
      p.z = z;
      std::pair< A*, Point > tp( this, p );
      pthread_create(&tid, NULL, func, &tp);
      pthread_join(tid, NULL);
    }
};

int main(int argc, char *argv[])
{

  A a;

  a.myFunc();

  return 0;
}

您可以使用std::tuple类传递this指针和多个参数。