为了账号安全,请及时绑定邮箱和手机立即绑定

类中的p线程函数。

类中的p线程函数。

C++
饮歌长啸 2019-06-18 15:06:06
类中的p线程函数。假设我有一个类似的类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);错误输出:无法转换‘void*(tree_tem:)(无效)“to”无效*()(无效)‘for参数’3‘to’int pline_create(p线程_t*,const p线程_attr_t*,void*()(无效),无效*‘
查看完整描述

3 回答

?
临摹微笑

TA贡献1982条经验 获得超2个赞

因为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);


查看完整回答
反对 回复 2019-06-18
?
至尊宝的传说

TA贡献1789条经验 获得超10个赞

我最喜欢的处理线程的方法是将它封装在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;};

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


查看完整回答
反对 回复 2019-06-18
?
12345678_0001

TA贡献1802条经验 获得超5个赞

你得给pthread_create一个与它正在寻找的签名相匹配的函数。你路过的都没用。

您可以实现任何您喜欢这样做的静态函数,并且它可以引用c在线程中执行你想要的。pthread_create设计为不仅接受函数指针,而且接受指向“上下文”的指针。在这种情况下,您只需将指向c.

例如:

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

    ...

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

    ...}


查看完整回答
反对 回复 2019-06-18
  • 3 回答
  • 0 关注
  • 505 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信