簡體   English   中英

使用 std::thread 在 C++ 中的單獨線程中執行每個對象

[英]Executing each Object in a seperate thread in C++ using std::thread

考慮如下所示的兩個類

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類之外的另一個線程中。 PS 這個問題是我之前提出的一個被擱置的問題的改寫版本。 我希望這次更清楚。

我想以這樣一種方式向用戶公開公共函數,每當用戶從類CommandChannel調用函數時,它們都在一個線程中運行,比如cChannelThread

在這種情況下,您需要將調用轉發到另一個線程。 這可以通過將帶有所有調用參數副本的函數指針/lambda 保存到std::function<void()>對象中,將該對象傳遞給另一個線程並調用該對象來完成。

如果你的函數返回別的東西然后void那么你需要一種機制來將返回值傳遞回調用線程。 有不止一種方法可以做到,您可以從使用std::packaged_task

要在線程之間傳遞對象,請使用原子隊列,例如英特爾並發隊列類

在線程之間共享對象時要小心。 如果一個對象在線程之間共享,並且至少有一個線程修改了該對象,則需要鎖定以防止競爭條件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM