考虑如下所示的两个类
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 saycChannelThread
在这种情况下,您需要将调用转发给另一个线程。这可以通过将函数指针/lambda 和所有调用参数的拷贝保存到 std::function<void()>
中来完成。对象,将该对象传递给另一个线程,并调用该对象。
如果您的函数返回其他内容,则 void
那么你需要一种机制将返回值传递回调用线程。有不止一种方法可以做到这一点,您可以从使用 std::packaged_task
开始。 .
要在线程之间传递对象,请使用原子队列,例如 Intel Concurrent Queue Classes .
在线程之间共享对象时要小心。如果一个对象在线程之间共享并且至少一个线程修改了该对象,则需要锁定以防止竞争条件。
关于c++ - 使用 std::thread 在 C++ 中的单独线程中执行每个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53320184/