簡體   English   中英

線程完成后在另一個線程中調用方法

[英]Calling a method in another thread after a thread is finished

我正在嘗試並行化程序,但是由於我對線程還很陌生,所以我遇到了一些問題。

我有兩個屬於同一類的方法。 一種方法在for循環中執行一些計算,然后將結果壓入向量,另一種方法(runTheResult)接受向量,並使用獲得的向量啟動線程。 我希望每次運行runTheResult時都會啟動另一個線程以運行下一個獲得的結果,同時將一次將最大線程數限制為4。

我的程序的結構如下:

void runTheResult(vector<double>& u){

//process 'u' and launch a thread 


};

void method(){

for(...){

//calculate

    for(...){

    //put the calculations in vector<double>result

    };

    runTheResult(result); 

};

};

我已經對此進行了很多搜索,其中一種解決方案是維護消息隊列。 但是,與此有關的問題是,如果我實現一個查詢,則必須在while循環中定期與另一個線程檢查該查詢。 如果我像while(true){//check for new messages if number of threads is less than five}那樣使用while循環while(true){//check for new messages if number of threads is less than five}while(true){//check for new messages if number of threads is less than five} ,我將失去很多處理能力,如果在條件不滿足的情況下選擇讓循環進入休眠狀態遇見,我浪費了處理能力。 我在線程中運行的函數每個需要2-5秒,而我必須處理其中的大約1k至50k,因此每個循環甚至一秒鍾的延遲都很大。

每次runTheResult完成時,是否可以在另一個線程中運行runTheResult? 還是有更好的方法做到這一點?

其他人則告訴您使用消息隊列,因為這是最安全的方法。 您的程序必須至少具有一個用戶(您或最終用戶)可以與之交互的主線程。 只要您的程序運行,該主線程就會一直循環。 您在這里進行郵件處理

// this is not actually running the result now
// this only sends it to the main thread that will run the result
void runTheResult(vector<double>& u){ 

    //process 'u' and launch a thread. 
    // @NOTE Launching a thread again will not be beneficial as it will still be blocked 
    // by the mutex

    // convert/store vector into Message. To make it usable for other types
    // or you can just change Message to double
    Message u_message = to_message(u)

    std::lock_guard<std::mutex> lock(message_mutex);
    messages_shared.append(u_message);

};

void method() // runs on worker thread
{
    for(...){

    //put the calculations in vector<double>result

    };

    runTheResult(result);
}

void getMessages_safe(std::vector<Messages>& outMessages_safe)
{
    // as Ted Lyngo suggests, using lock_guard is best practice. See edit for alternative
    std::lock_guard<std::mutex> lock(message_mutex);
    outMessages_safe = messages_shared;
    messages_shared.clear();
}

std::vector<Message> messages_shared;
std::mutex message_mutex;

void main() { // this runs on the very first thread of the program
  while (isProgramRunning)
  {
      std::vector<Message> messages_safe; // safe to access by this thread only
      getMessages_safe(messages_safe);

      // dispatch messages to whoever needs it

      // launch worker thread
  }
}

暫無
暫無

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

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