簡體   English   中英

使用std :: thread從C ++ 11中的兩個類調用函數

[英]Using std::thread to call functions from two Classes in C++11

我正在嘗試實現一個API,該API應該允許用戶並行創建兩個通信通道。 一個通道使用TCP,另一個通道使用UDP。 我有兩個代表兩個渠道的班級。 這些類實現了不同的功能。 我希望兩個通道中的函數並行運行。 為此,我使用std::thread創建兩個線程,每個通道(類)一個。 這個想法是下面的頭文件看起來像

class Channel_1
{
public:
     int myfunc(int a, int b);
};

class Channel_2
{
public:
    int anotherfunc(int a, int b);
};

在主cpp文件中包括頭文件

int main()
{
  int a = 10, b = 20;
  Channel_1 ch1;
  Channel_2 ch2;

  std::thread t(ch1.myfunc, a,b);
  return 0;
}

我收到錯誤消息,指出不存在構造函數std::thread實例。

我有以下問題。

  1. 我們不能從線程構造函數中的類調用函數嗎?
  2. 使用線程從不同類調用函數的這種想法有意義嗎?

您實際上有兩個問題:

  1. 語法錯誤。 您需要傳遞一個指向成員函數的指針,如

     std::thread t(&Channel_1::myfunc, a, b); 
  2. 非靜態成員函數需要在類的實例上調用。 該實例必須作為第一個參數傳遞:

     std::thread t(&Channel_1::myfunc, ch1, a, b); 

就像一些程序員所說的那樣,您需要提供一個指向函數的指針(靜態或非靜態)。 第三種選擇是制作一個基類,該基類實現使用此線程構造函數的start()方法:

template< class Function, class... Args > 
explicit thread( Function&& f, Args&&... args );

使用lambda的示例。 它並不意味着是一個完整的工作示例,這只是意在顯示第三線的構造如何被使用。

class thread_base {
private:
    std::thread m_th;
    bool m_terminated;

    void proxy() {
        // in the new thread
        // add thread_base setup here if needed and
        // call the execute() method in the derived class
        execute();
    }
public:
    thread_base() : m_th(), m_terminated(false) {}
    thread_base(const thread_base&) = delete;
    thread_base& operator=(const thread_base&) = delete;
    thread_base(thread_base&&) = default;
    thread_base& operator=(thread_base&&) = default;
    virtual ~thread_base() { join(); }

    virtual void start() {
        if(joinable()) throw std::runtime_error("thread already running");
        else m_th = std::thread( [this] { proxy(); } );
    }

    inline bool joinable() { return m_th.joinable(); }
    inline void join() { if(joinable()) { m_th.join(); m_terminated=false; } }
    inline void terminate() { m_terminated=true; }
    inline bool terminated() { return m_terminated; }

    virtual void execute() = 0; // implement this in your derived classes
};


class Channel_1 : public thread_base {
    void execute() {
        // runs in a thread
        // with a volontary check if a soft termination
        // request has been issued
        while( !terminated() ) {
            // work
        }
    }
};

暫無
暫無

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

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