从一个类中使用pthread函数

96

假设我有一个类,比如:

class c { 
    // ...
    void *print(void *){ cout << "Hello"; }
}

然后我有一个c的向量

vector<c> classes; pthread_t t1;
classes.push_back(c());
classes.push_back(c());

现在,我想在c.print();上创建一个线程。

下面的代码给我的问题如下:

pthread_create(&t1, NULL, &c[0].print, NULL);

错误输出:无法将'tree_item :: *()(void *)'转换为' void *(*)(void *)',对于参数'3',以'int pthread_create(pthread_t *,const pthread_attr_t *,void *(*)(void *),void *)'形式'

9个回答

161
您不能按照您编写的方式进行操作,因为C++类成员函数会传递隐藏的“this”参数。因此,如果您尝试通过将该方法强制转换为适当类型的函数指针来绕过编译器,那么pthread_create()无法确定使用哪个this值,这将导致段错误。您必须使用静态类方法(没有this参数)或普通函数来引导类:
class C
{
public:
    void *hello(void)
    {
        std::cout << "Hello, world!" << std::endl;
        return 0;
    }

    static void *hello_helper(void *context)
    {
        return ((C *)context)->hello();
    }
};
...
C c;
pthread_t t;
pthread_create(&t, NULL, &C::hello_helper, &c);

@Chris:我不想就类型转换风格展开一场圣战,但在这种情况下使用C风格的类型转换是完全符合语义的。 - Adam Rosenfield
2
@AdamRosenfield 连接副词在语义上也是完全正确的,但这并不意味着它是好的风格!xD - ACK_stoverflow
很好的答案,但是我在G++(4.7)上遇到了编译错误。为了解决这个问题,我从helper(hello_helper)方法中删除了return语句。 - Ian Link
@AdamRosenfield:我曾经做过类似的实现,其中我使用了pthread_create(&this->thread, NULL, this->functionPointer, NULL);。这里的functionPointer是一个类成员,并且在每个对象实例化时将指向普通函数的指针分配给该指针。然后它作为参数传递给pthread_create,并作为this->functionPointer。令人惊讶的是,它确实起作用。您可以在此处查看代码:[link]http://paste.ofcode.org/ETKUd2LS8XejYtskmDwBeu。您说`pthread_create`不知道`this`是什么。那么,您能解释一下这里的`this`是如何工作的吗? - Rohit
@Rohit:你的线程过程 threadOne() 从未尝试使用其参数 args。如果它这样做,它将得到 NULL,并且无法访问 Thread 对象实例。那里有什么令人惊讶的? - Adam Rosenfield
显示剩余7条评论

86

我处理线程的最喜欢方法是将其封装在一个C++对象中。下面是一个例子:

class MyThreadClass
{
public:
   MyThreadClass() {/* empty */}
   virtual ~MyThreadClass() {/* empty */}

   /** Returns true if the thread was successfully started, false if there was an error starting the thread */
   bool StartInternalThread()
   {
      return (pthread_create(&_thread, NULL, InternalThreadEntryFunc, this) == 0);
   }

   /** Will not return until the internal thread has exited. */
   void WaitForInternalThreadToExit()
   {
      (void) pthread_join(_thread, NULL);
   }

protected:
   /** Implement this method in your subclass with the code you want your thread to run. */
   virtual void InternalThreadEntry() = 0;

private:
   static void * InternalThreadEntryFunc(void * This) {((MyThreadClass *)This)->InternalThreadEntry(); return NULL;}

   pthread_t _thread;
};

为使用它,您只需创建MyThreadClass的子类,并实现InternalThreadEntry()方法来包含您的线程事件循环。当然,在删除线程对象之前,您需要在线程对象上调用WaitForInternalThreadToExit()(并有一些机制确保线程实际退出,否则WaitForInternalThreadToExit()将永远不会返回)。


1
这是我能理解上述虚拟类使用的好方法,但我有更深层次的问题。我有一些生成其他线程的线程,需要全部放入一个向量中。然后进行递归循环以加入所有线程。我相信我也可以通过在正确的位置调用等待来实现上述操作,但我会尝试一下看看我能到哪里。 - Angel.King.47
4
这个解决方案非常优雅,我以后会使用它。谢谢Jeremy Friesner。 +1 - Armada
你好,Jeremy Friesner,如何传递一个对InternalThreadEntry的引用(aclass_ref&refobj)?我应该做哪些更改? - uss
@sree 将MyThreadClass的引用(或指针)作为成员变量添加;然后InternalThreadEntry()可以直接访问它,而不必担心通过(void *)参数传递它。 - Jeremy Friesner

10

你需要给pthread_create提供一个与其所期望的签名匹配的函数。你现在传递的不起作用。

你可以实现任何静态函数来做这个,它可以引用一个实例并在线程中执行你想要的操作。 pthread_create不仅接受函数指针,还接受指向“上下文”的指针。在这种情况下,你只需传递指向实例的指针即可。

例如:

static void* execute_print(void* ctx) {
    c* cptr = (c*)ctx;
    cptr->print();
    return NULL;
}


void func() {

    ...

    pthread_create(&t1, NULL, execute_print, &c[0]);

    ...
}

1
哦,我明白你的意思了。把c的指针传递进去,好的,我会实现并尝试一下。 - Angel.King.47

4
上述答案很好,但在我的情况下,将函数转换为静态函数的第一种方法不起作用。我试图将现有代码转换为线程函数,但该代码已经引用了许多非静态类成员。将其封装为C++对象的第二个解决方案可行,但需要三层包装才能运行线程。
我有一个备选方案,使用现有的C++构造 - “友元”函数,这对我的情况非常完美。 以下是我如何使用“友元”的示例(将使用上面相同的名称示例,以显示如何使用“友元”将其转换为紧凑形式)。
    class MyThreadClass
    {
    public:
       MyThreadClass() {/* empty */}
       virtual ~MyThreadClass() {/* empty */}

       bool Init()
       {
          return (pthread_create(&_thread, NULL, &ThreadEntryFunc, this) == 0);
       }

       /** Will not return until the internal thread has exited. */
       void WaitForThreadToExit()
       {
          (void) pthread_join(_thread, NULL);
       }

    private:
       //our friend function that runs the thread task
       friend void* ThreadEntryFunc(void *);

       pthread_t _thread;
    };

    //friend is defined outside of class and without any qualifiers
    void* ThreadEntryFunc(void *obj_param) {
    MyThreadClass *thr  = ((MyThreadClass *)obj_param); 

    //access all the members using thr->

    return NULL;
    }

当然,我们可以使用boost::thread来避免所有这些问题,但我试图修改C++代码以便不使用boost(该代码仅出于此目的而链接到boost)。

1

我希望这是对某人有用的第一个答案: 我现在遇到了与上述问题完全相同的错误,因为我正在编写一个TcpServer类并尝试使用pthread。我发现了这个问题,现在我明白了为什么会出现这种情况。最终,我做了这个:

#include <thread>

运行线程的方法 -> void* TcpServer::sockethandler(void* lp) {/*在此处编写代码*/}

我使用lambda调用它 -> std::thread( [=] { sockethandler((void*)csock); } ).detach();

这对我来说是一种简洁的方法。


0

我发现很多次,解决你所要求的问题的方法,在我看来都太复杂了。例如,你必须定义新的类类型,链接库等等。因此,我决定写几行代码,让最终用户能够基本上“线程化”任何类的“void ::method(void)”。

当然,我实现的这个解决方案可以扩展、改进等等,所以,如果你需要更具体的方法或功能,请添加它们,并请好心通知我。

这里有三个文件展示了我所做的。

    // A basic mutex class, I called this file Mutex.h
#ifndef MUTEXCONDITION_H_
#define MUTEXCONDITION_H_

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

class MutexCondition
{
private:
    bool init() {
        //printf("MutexCondition::init called\n");
        pthread_mutex_init(&m_mut, NULL);
        pthread_cond_init(&m_con, NULL);
        return true;
    }

    bool destroy() {
        pthread_mutex_destroy(&m_mut);
        pthread_cond_destroy(&m_con);
        return true;
    }

public:
    pthread_mutex_t m_mut;
    pthread_cond_t m_con;

    MutexCondition() {
        init();
    }
    virtual ~MutexCondition() {
        destroy();
    }

    bool lock() {
        pthread_mutex_lock(&m_mut);
        return true;
    }

    bool unlock() {
        pthread_mutex_unlock(&m_mut);
        return true;
    }

    bool wait() {
        lock();
        pthread_cond_wait(&m_con, &m_mut);
        unlock();
        return true;
    }

    bool signal() {
        pthread_cond_signal(&m_con);
        return true;
    }
};
#endif
// End of Mutex.h

// 封装了将方法线程化的所有工作的类(test.h):

#ifndef __THREAD_HANDLER___
#define __THREAD_HANDLER___

#include <pthread.h>
#include <vector>
#include <iostream>
#include "Mutex.h"

using namespace std;

template <class T> 
class CThreadInfo
{
  public:
    typedef void (T::*MHT_PTR) (void);
    vector<MHT_PTR> _threaded_methods;
    vector<bool> _status_flags;
    T *_data;
    MutexCondition _mutex;
    int _idx;
    bool _status;

    CThreadInfo(T* p1):_data(p1), _idx(0) {}
    void setThreadedMethods(vector<MHT_PTR> & pThreadedMethods)
    {
        _threaded_methods = pThreadedMethods;
      _status_flags.resize(_threaded_methods.size(), false);
    }
};

template <class T> 
class CSThread {
  protected:
    typedef void (T::*MHT_PTR) (void);
    vector<MHT_PTR> _threaded_methods;
    vector<string> _thread_labels;
    MHT_PTR _stop_f_pt;
    vector<T*> _elements;
    vector<T*> _performDelete;
    vector<CThreadInfo<T>*> _threadlds;
    vector<pthread_t*> _threads;
    int _totalRunningThreads;

    static void * gencker_(void * pArg)
    {
      CThreadInfo<T>* vArg = (CThreadInfo<T> *) pArg;
      vArg->_mutex.lock();
      int vIndex = vArg->_idx++;
      vArg->_mutex.unlock();

      vArg->_status_flags[vIndex]=true;

      MHT_PTR mhtCalledOne = vArg->_threaded_methods[vIndex];
      (vArg->_data->*mhtCalledOne)();
      vArg->_status_flags[vIndex]=false;
        return NULL;
    }

  public:
    CSThread ():_stop_f_pt(NULL), _totalRunningThreads(0)  {}
    ~CSThread()
    {
      for (int i=_threads.size() -1; i >= 0; --i)
          pthread_detach(*_threads[i]);

      for (int i=_threadlds.size() -1; i >= 0; --i)
        delete _threadlds[i];

      for (int i=_elements.size() -1; i >= 0; --i)
         if (find (_performDelete.begin(), _performDelete.end(), _elements[i]) != _performDelete.end())
              delete _elements[i];
    }
    int  runningThreadsCount(void) {return _totalRunningThreads;}
    int  elementsCount()        {return _elements.size();}
    void addThread (MHT_PTR p, string pLabel="") { _threaded_methods.push_back(p); _thread_labels.push_back(pLabel);}
    void clearThreadedMethods() { _threaded_methods.clear(); }
    void getThreadedMethodsCount() { return _threaded_methods.size(); }
    void addStopMethod(MHT_PTR p)  { _stop_f_pt  = p; }
    string getStatusStr(unsigned int _elementIndex, unsigned int pMethodIndex)
    {
      char ch[99];

      if (getStatus(_elementIndex, pMethodIndex) == true)
        sprintf (ch, "[%s] - TRUE\n", _thread_labels[pMethodIndex].c_str());
      else 
        sprintf (ch, "[%s] - FALSE\n", _thread_labels[pMethodIndex].c_str());

      return ch;
    }
    bool getStatus(unsigned int _elementIndex, unsigned int pMethodIndex)
    {
      if (_elementIndex > _elements.size()) return false;
      return _threadlds[_elementIndex]->_status_flags[pMethodIndex];
    }

    bool run(unsigned int pIdx) 
    {
      T * myElem = _elements[pIdx];
      _threadlds.push_back(new CThreadInfo<T>(myElem));
      _threadlds[_threadlds.size()-1]->setThreadedMethods(_threaded_methods);

      int vStart = _threads.size();
      for (int hhh=0; hhh<_threaded_methods.size(); ++hhh)
          _threads.push_back(new pthread_t);

      for (int currentCount =0; currentCount < _threaded_methods.size(); ++vStart, ++currentCount)
      {
                if (pthread_create(_threads[vStart], NULL, gencker_, (void*) _threadlds[_threadlds.size()-1]) != 0)
        {
                // cout <<"\t\tThread " << currentCount << " creation FAILED for element: " << pIdx << endl;
                    return false;
                }
        else
        {
            ++_totalRunningThreads;
             // cout <<"\t\tThread " << currentCount << " creation SUCCEDED for element: " << pIdx << endl;
                }
      }
      return true;
    }

    bool run() 
    {
            for (int vI = 0; vI < _elements.size(); ++vI) 
            if (run(vI) == false) return false;
          // cout <<"Number of currently running threads: " << _totalRunningThreads << endl;
        return true;
    }

    T * addElement(void)
    {
      int vId=-1;
      return addElement(vId);
    }

    T * addElement(int & pIdx)
    {
      T * myElem = new T();
      _elements.push_back(myElem);
      pIdx = _elements.size()-1;
      _performDelete.push_back(myElem);
      return _elements[pIdx];
    }

    T * addElement(T *pElem)
    {
      int vId=-1;
      return addElement(pElem, vId);
    }

    T * addElement(T *pElem, int & pIdx)
    {
      _elements.push_back(pElem);
      pIdx = _elements.size()-1;
      return pElem;
    }

    T * getElement(int pId) { return _elements[pId]; }

    void stopThread(int i)  
    {
      if (_stop_f_pt != NULL) 
      {
         ( _elements[i]->*_stop_f_pt)() ;
      }
      pthread_detach(*_threads[i]);
      --_totalRunningThreads;
    }

    void stopAll()  
    {
      if (_stop_f_pt != NULL) 
        for (int i=0; i<_elements.size(); ++i) 
        {
          ( _elements[i]->*_stop_f_pt)() ;
        }
      _totalRunningThreads=0;
    }
};
#endif
// end of test.h

//一个用法示例文件“test.cc”,在Linux上我已经编译并使用了 封装所有线程化方法工作的类: g++ -o mytest.exe test.cc -I. -lpthread -lstdc++

#include <test.h>
#include <vector>
#include <iostream>
#include <Mutex.h>

using namespace std;

// Just a class for which I need to "thread-ize" a some methods
// Given that with OOP the objecs include both "functions" (methods)
// and data (attributes), then there is no need to use function arguments,
// just a "void xxx (void)" method.
// 
class TPuck
{
  public:
   bool _go;
   TPuck(int pVal):_go(true)
   {
     Value = pVal;
   }
   TPuck():_go(true)
   {
   }
   int Value;
   int vc;

   void setValue(int p){Value = p; }

   void super()
   {
     while (_go)
     {
      cout <<"super " << vc << endl;
            sleep(2);
         }
      cout <<"end of super " << vc << endl;
   }

   void vusss()
   {
     while (_go)
     {
      cout <<"vusss " << vc << endl;
      sleep(2);
     }
      cout <<"end of vusss " << vc << endl;
   }

   void fazz()
   {
     static int vcount =0;
     vc = vcount++;
     cout <<"Puck create instance: " << vc << endl;
     while (_go)
     {
       cout <<"fazz " << vc << endl;
       sleep(2);
     }
     cout <<"Completed TPuck..fazz instance "<<  vc << endl;
   }

   void stop()
   {
      _go=false;
      cout << endl << "Stopping TPuck...." << vc << endl;
   }
};


int main(int argc, char* argv[])
{
  // just a number of instances of the class I need to make threads
  int vN = 3;

  // This object will be your threads maker.
  // Just declare an instance for each class
  // you need to create method threads
  //
  CSThread<TPuck> PuckThreadMaker;
  //
  // Hera I'm telling which methods should be threaded
  PuckThreadMaker.addThread(&TPuck::fazz, "fazz1");
  PuckThreadMaker.addThread(&TPuck::fazz, "fazz2");
  PuckThreadMaker.addThread(&TPuck::fazz, "fazz3");
  PuckThreadMaker.addThread(&TPuck::vusss, "vusss");
  PuckThreadMaker.addThread(&TPuck::super, "super");

  PuckThreadMaker.addStopMethod(&TPuck::stop);

  for (int ii=0; ii<vN; ++ii)
  {
    // Creating instances of the class that I need to run threads.
    // If you already have your instances, then just pass them as a
    // parameter such "mythreadmaker.addElement(&myinstance);"
    TPuck * vOne = PuckThreadMaker.addElement();
  }

  if (PuckThreadMaker.run() == true)
  {
    cout <<"All running!" << endl;
  }
  else
  {
    cout <<"Error: not all threads running!" << endl;
  }

  sleep(1);
  cout <<"Totale threads creati: " << PuckThreadMaker.runningThreadsCount()  << endl;
  for (unsigned int ii=0; ii<vN; ++ii)
  {
    unsigned int kk=0;
    cout <<"status for element " << ii << " is " << PuckThreadMaker.getStatusStr(ii, kk++) << endl; 
    cout <<"status for element " << ii << " is " << PuckThreadMaker.getStatusStr(ii, kk++) << endl; 
    cout <<"status for element " << ii << " is " << PuckThreadMaker.getStatusStr(ii, kk++) << endl; 
    cout <<"status for element " << ii << " is " << PuckThreadMaker.getStatusStr(ii, kk++) << endl; 
    cout <<"status for element " << ii << " is " << PuckThreadMaker.getStatusStr(ii, kk++) << endl; 
  }

  sleep(2);
  PuckThreadMaker.stopAll();
  cout <<"\n\nAfter the stop!!!!" << endl;
  sleep(2);

  for (int ii=0; ii<vN; ++ii)
  {
    int kk=0;
    cout <<"status for element " << ii << " is " << PuckThreadMaker.getStatusStr(ii, kk++) << endl; 
    cout <<"status for element " << ii << " is " << PuckThreadMaker.getStatusStr(ii, kk++) << endl; 
    cout <<"status for element " << ii << " is " << PuckThreadMaker.getStatusStr(ii, kk++) << endl; 
    cout <<"status for element " << ii << " is " << PuckThreadMaker.getStatusStr(ii, kk++) << endl; 
    cout <<"status for element " << ii << " is " << PuckThreadMaker.getStatusStr(ii, kk++) << endl; 
  }

  sleep(5);
  return 0;
}

// End of test.cc

0

这是一个有点老的问题,但很常见,许多人都会遇到。 以下是使用std :: thread处理此问题的简单而优雅的方法

#include <iostream>
#include <utility>
#include <thread>
#include <chrono>

class foo
{
    public:
        void bar(int j)
        {
            n = j;
            for (int i = 0; i < 5; ++i) {
                std::cout << "Child thread executing\n";
                ++n;
                std::this_thread::sleep_for(std::chrono::milliseconds(10));
            }
        }
        int n = 0;
};

int main()
{
    int n = 5;
    foo f;
    std::thread class_thread(&foo::bar, &f, n); // t5 runs foo::bar() on object f
    std::this_thread::sleep_for(std::chrono::milliseconds(20));
    std::cout << "Main Thread running as usual";
    class_thread.join();
    std::cout << "Final value of foo::n is " << f.n << '\n';
}

以上代码还负责将参数传递给线程函数。
请参阅std::thread文档以获取更多详细信息。

-1

-1
我的猜测是这可能是因为C++将其弄乱了一点,因为您正在发送一个C++指针而不是C函数指针。 显然有一个difference。 尝试执行


(void)(*p)(void) = ((void) *(void)) &c[0].print; //(check my syntax on that cast)

然后发送p。

我也用成员函数做了你正在做的事情,但是我是在使用它的类中使用静态函数 - 我认为这是不同之处。


我尝试了上面的方法,但是出现了语法错误。我也试着改变了一下...如果您能够友善地展示如何使用pthread_create(...),那将会很有帮助。 - Angel.King.47

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接