2016-01-21 21 views
-1

我上課,讓我們把它稱爲「引擎」,它包含類似事件循環的邏輯都可以由下面的僞代碼來說明:如何實現引擎類,它不會阻止它的用戶

for(;;) { 
    int interruptId; 
    waitForInterrupt(); // blocking wait 
    switch(interruptId) { 
    case REQUEST_DATA: 
    doSomeStuff(); 

    ... 
    } 
} 

事件循環用於中斷處理(來自硬件設備的驅動程序)。 引擎將被客戶端使用。客戶應該能夠啓動/停止引擎。 但啓動引擎不應該掛起客戶端。

我的意圖:當Engine啓動時,它啓動一個新的線程,其中執行(;;)的事件循環。

問題是一個解決方案,你能否提出適用於這種情況的現有設計模式,以及我應該考慮的任何實現建議和可能的瓶頸。

NB!更新:引擎類是提供給客戶作爲一個動態庫

+0

如果您的客戶端已經有一個事件循環,可以將發動機事件循環合併到它,如果你想避免額外的線程。 –

+0

引擎類作爲一個單獨的動態庫提供給客戶端,所以我不能合併它們的循環 –

+0

「合併」可能是一個糟糕的選擇 - 怎麼樣「來自」 - 即。對於每個客戶端事件循環迭代,還要檢查引擎是否有未決事件(如果是,則處理引擎事件 - 如果不是,則只執行下一次客戶端循環迭代)。 –

回答

0
#include <thread> 
#include <functional> 
#include <vector> 
#include <iostream> 
#include <memory> 
#include <cassert> 

struct MsgFromAgent { 
    std::string str; 
}; 

struct MsgToAgent { 
    std::string str; 
}; 

struct IClient { 
    virtual void onMsgFromBC(MsgFromAgent& msg) = 0; 
    virtual void onTimeout() = 0; 
    virtual ~IClient() {}; 
}; 

struct Engine { 
    Engine(IClient& client) : isRunning(false), client(client) { } 
    ~Engine() { 
    // we expect that if client started the engine 
    // client must stop it before Engine will be destructed 
    assert(!isRunning && "Running engine should be stoped by the client"); 

    // in any way, handle exceptional situation if it arises 
    if(isRunning) { 
     isRunning = false; 
     th.join(); 
    } 
    } 
    void start() { 
    isRunning = true; 
    th = std::thread(std::bind(&Engine::eventLoop, this)); 
    } 
    bool write(const MsgToAgent& msg) { 
    // some code 
    } 
    void stop() { 
    isRunning = false; 
    th.join(); 
    } 
    void eventLoop() { 
    while(isRunning) { 
     // blocking calls, that return control when certain interrupts from hardware arrives 

     // if interrupt haven't arraived within certain time limit: 
     try { 
     client.onTimeout(); 
     } catch(...) { 

     } 

     // interrupt about incomming msg: 
     MsgFromAgent dummyMsg; 
     try { 
     client.onMsgFromBC(dummyMsg); 
     } 
     catch (...) { 

     } 
    } 
    } 
    bool isRunning; 
    std::thread th; 
    IClient& client; 
}; 

struct Client : public IClient { 
    Client() : e(*this) { 

    }; 
    ~Client() { 
    } 
    void onMsgFromBC(MsgFromAgent& msg) { 
    std::cout << "On message\n"; 
    } 
    void onTimeout() { 
    std::cout << "On timeout\n"; 
    } 
    Engine e; 
}; 

int main() { 
    Client c; 
    return 0; 
} 
相關問題