使用std :: thread在C ++中的单独线程中执行每个对象

时间:2018-11-15 13:07:17

标签: c++ multithreading

考虑如下所示的两个类

class CommandChannel
{
private:
    std::thread cChannelThread;
public:
    CommandChannel();
    ~CommandChannel();

    void start_comm_channel(int port, std::string ip);

    int myfunction(int a, int b);
    double otherfunction(std::string test);

    void stop_comm_channel();
};


class EventChannel
{
private:
    std::thread evChannelThread;
public:
    EventChannel();
    ~EventChannel();

    void start_ev_chnl(int port, std::string ip);

    int evFunction(int a, int b);
    double anotherfunction(std::string othertest);

    void stop_ev_chnl();
};

我想以这样一种方式向用户公开公共功能:无论何时用户从类CommandChannel调用函数,它们都在一个线程中运行,例如cChannelThread。每当用户从类EventChannel调用函数时,它们便在另一个线程evChannelThread中运行。 我不确定这是否是一个好主意,但是我是C ++的新手,尤其是多线程的新手。基本思想是将EventChannel类完全保留在CommandChannel类之外的另一个线程中。 附言:该问题是我先前提出的被搁置的问题的重述版本。我希望这次更加清楚。

1 个答案:

答案 0 :(得分:1)

  

我想以这样一种方式向用户公开公共功能:无论何时用户从类CommandChannel调用函数,它们都在一个线程中运行,例如cChannelThread

在这种情况下,您需要将调用转发到另一个线程。这可以通过将函数指针/ lambda和所有调用参数的副本保存到std::function<void()>对象中,将该对象传递给另一个线程,然后调用该对象来实现。

如果您的函数返回了其他内容,则void则需要一种将返回值传递回调用线程的机制。有多种方法可以做到,您可以从使用std::packaged_task开始。

要在线程之间传递对象,请使用原子队列,例如Intel Concurrent Queue Classes

在线程之间共享对象时要小心。如果一个对象在线程之间共享,并且至少有一个线程修改了该对象,则需要锁定以防止出现竞争状况。