2014-06-27 41 views
2

我想提供一個類,它在讀取某些數據(udp數據包或來自文件)時保存緩衝區。一切都很好,如果我從主開始我的線程,但在這種情況下,我想避免,用戶必須爲自己設置一個新的線程。C++ 11線程 - 從類內部開始無限工作線程

所以這裏是我的代碼那樣簡單我可以使它:

class DataCollector 
{ 
    void startCollect() 
    { 
     std::thread t1(readSource); 
    } 

    bool readSource() 
    { 
     while(1) 
     { 
      // read some data for storage 
     } 
    } 
} 

int main() 
{ 
    DataCollector myDataCollector; 
    myDataCollector.startCollect(); 

    while(1) 
    { 
     // do some other work, for example interpret the data 
    } 

    return 0; 
} 

現在我需要你的幫助。如何在startCollect中調用此線程?

編輯1: 這裏是我如何工作的例子現在!

// ringbuffertest.cpp : Definiert den Einstiegspunkt für die Konsolenanwendung. 
// 

#include "stdafx.h" 
#include <thread> 
#include <Windows.h> 

class DataCollector 
{ 
private: 
    //std::thread collecterThread; 

public: 
    DataCollector(){} 

    void startCollect() 
    {  
     readSource(); 
    } 

    bool readSource() 
    { 
     while (1) 
     { 
      printf("Hello from readSource!\n"); 
      Sleep(1000); 
     } 
     return false; 
    } 
}; 


int _tmain(int argc, _TCHAR* argv[]) 
{ 
    DataCollector myDataCollector; 

    std::thread t1(&DataCollector::startCollect, std::ref(myDataCollector)); 

    t1.join(); 
    return 0; 
} 

但正如我所說我想隱藏我的startCollect函數內的線程調用。

+2

線程不應該是DataCollector的屬性嗎?然後你可以在構造函數中實例化它並在startCollect中啓動它。 –

+0

您將需要一個緩衝區(或兩個)並使用condition_variable通知每個線程已提供一些數據。 –

+0

你我知道我的緩衝區。我只是從我的程序中扔出一切,使其儘可能簡單。 –

回答

1

之前破壞活動thread對象,它必須是加入(等待線程結束,然後清理其資源)或分離(左運行,完成後清理本身上)。

所以,你既可以使線程一個成員變量,以便它可以在稍後加入:

void startCollect() 
{ 
    this->thread = std::thread(&DataCollector::readSource, this); 
} 

void waitForCollectToFinish() 
{ 
    this->thread.join(); 
} 

或者你可以脫離它,如果你不需要等待它完成的能力,並有信令數據的其他方式可供選擇:

void startCollect() 
{ 
    std::thread([this]{readSource();}).detach(); 
} 

你也可以看看更高級別的併發性設施,如std::asyncstd::future。這些可能比直接處理線程更方便。

+0

您可以在[coliru]上看到此方法(http://coliru.stacked-crooked.com/a/87b6ee616f912cd9)。 –

+0

this-> thread = std :: thread(readSource,this);我得到編譯器錯誤。我將編輯一個工作示例(其中我從main開始線程)。 –

+0

@ user3783662:你說得對,應該是'&DataCollection :: readSource'。或者,也許更具可讀性,lambda'[this] {readSource();}'。 –