【问题标题】:Thread and interfaces C++线程和接口 C++
【发布时间】:2015-06-25 06:15:57
【问题描述】:

我在使用接口和工厂创建不同的线程时遇到了一些问题:

我有两个派生的接口(这里是一个类,但最终更多......)。我使用工厂来创建所需派生类的对象。 当我在不同的线程中运行它们时,我使用工厂返回给我的作为线程构造函数的参数。

#include <iostream>
#include <thread>

class Base
{
    public:
        virtual ~Base () {}

        virtual void operator () () = 0;
};


class Derived : public Base
{
    public:
        virtual void operator () ()
        {
            std::cout << "Derived of Base!" << std::endl;
        }
};

enum BaseType
{
    derived = 1000
};

class BaseFactory
{
    public:
        static Base *createBase (BaseType bt)
        {
            switch (bt)
            {
                case derived:
                    return new Derived;
                default:
                    return NULL;
            }
        }
};


class OtherBase
{
    public:
        virtual ~OtherBase () {}

        virtual void operator () () = 0;
};

class OtherDerived : public OtherBase
{
    public:
        virtual void operator () ()
        {
            std::cout <<  "OtherDerived of OtherBase!" << std::endl;
        }
};

enum OtherBaseType
{
    otherderived = 1100
};

class OtherBaseFactory
{
    public:
        static OtherBase *createOtherBase (OtherBaseType obt)
        {
            switch (obt)
            {
                case otherderived:
                    return new OtherDerived;
                default:
                    return NULL;
            }
        }
};



int main (int argc, const char *argv[])
{
    Base *pBase = BaseFactory::createBase(derived);
    OtherBase *pOBase = OtherBaseFactory::createOtherBase(otherderived);

    std::thread *t1 = new std::thread ((*pBase)());
    std::thread *t2 = new std::thread ((*pOBase)());

    t1->join();
    t2->join();

    delete t1;
    delete t2;

    return 0;
}

编译时,每个线程的创建都有问题:

test.cxx:87:50: error: invalid use of void expression
test.cxx:88:51: error: invalid use of void expression

我相信问题出在我作为参数创建 Base 和 OtherBase 类型的线程对象(因此是接口)。 但是我真的不知道如何解决这个问题。

【问题讨论】:

  • 您是在调用函子,而不是将它们传递给要调用的线程。

标签: c++ multithreading interface functor


【解决方案1】:

std::thread的构造函数可以将成员函数指针作为第一个参数,并会自动解引用并调用第二个参数上的成员函数指针。

因此,你可以这样写:

std::thread *t1 = new std::thread (&Base::operator(), pBase);
std::thread *t2 = new std::thread (&OtherBase::operator(), pOBase);

这可能比使用std::bind 更简单。

【讨论】:

  • 顺便谢谢你。我不知道这个构造函数。
  • 是的,确实更简单,更易读!谢谢你帮助我:)
【解决方案2】:

正如编译器所说 - 您要求创建参数设置为 void 的线程。 这是因为你通过(*pBase)()调用了对象函数(operator())。

我想您需要创建一个绑定到适当对象的函数。您可以像这样使用 std::bind 做到这一点:

std::bind(&Base::operator(), pBase)

所以线程创建应该是这样的:

std::thread *t1 = new std::thread (std::bind(&Base::operator(), pBase));

【讨论】:

  • 谢谢,现在可以了!你拯救了我的一天:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-22
  • 1970-01-01
  • 2016-03-16
  • 2012-09-07
  • 1970-01-01
  • 1970-01-01
  • 2016-02-16
相关资源
最近更新 更多