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

标签 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();
};

我想以这样一种方式向用户公开公共(public)函数,即每当用户调用类 CommandChannel 中的函数时,它们都在一个线程中运行,比如 cChannelThread .每当用户调用 EventChannel 类的函数时,它们都会在另一个线程 evChannelThread 中运行。 我不确定这是否是个好主意,但我是 C++ 的新手,尤其是多线程的新手。基本思想是将 EventChannel 类完全保留在另一个线程中,而不是 CommandChannel 类。 P.S 这个问题是我之前提出的一个被搁置的问题的改写版本。我希望这次更清楚。

最佳答案

I want to expose the public functions to a user in such a way that whenever the user calls the functions from the class CommandChannel they are run in one thread say cChannelThread

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

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

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

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

关于c++ - 使用 std::thread 在 C++ 中的单独线程中执行每个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53320184/

相关文章:

c++ - 使用 MS Visual C++ 2010 'sys/resource.h' : No such file 编译 C

c++ - 获取错误的毫秒延迟值

java - 线程并发——同步和锁。

java - 获取 Java ProgressMonitor 的取消事件

c++ - 如何避免序列化器和容器序列化器之间的循环模板依赖?

c++ - 构造函数错误

iphone - 当应用程序返回前台时,子线程随机被杀死

multithreading - 如何限制 perl 中的最大并行线程数

c++ - 模板函数调用类中的 protected 方法?

java - 多线程,java聊天客户端