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



考虑如下所示的两个类

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类之外的另一个线程中。P.S这个问题是我之前问的一个问题的改写版,这个问题被搁置了。我希望这次更清楚。

我想向用户公开公共函数,这样每当用户从类CommandChannel调用函数时,它们都会在一个线程中运行,比如cChannelThread

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

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

为了在线程之间传递对象,请使用原子队列,例如"英特尔并发队列类"。

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

最新更新