2012-11-03 28 views
4

我對C++非常陌生。如何在類函數內部創建線程?

我有一個類,我想在類的函數內部創建一個線程。並且該線程(函數)將調用並訪問類函數和變量。 一開始我試圖使用Pthread,但只能在類外部工作,如果我想訪問類函數/變量,我得到了超出範圍的錯誤。 我看看Boost /線程,但它不是我想要的,因爲我不想將任何其他庫添加到我的文件(出於其他原因)。

我做了一些研究,找不到任何有用的答案。 請舉一些例子來指導我。非常感謝!

嘗試使用並行線程(但我不知道該如何處理我上述的情況):

#include <pthread.h> 

void* print(void* data) 
{ 
    std::cout << *((std::string*)data) << "\n"; 
    return NULL; // We could return data here if we wanted to 
} 

int main() 
{ 
    std::string message = "Hello, pthreads!"; 
    pthread_t threadHandle; 
    pthread_create(&threadHandle, NULL, &print, &message); 
    // Wait for the thread to finish, then exit 
    pthread_join(threadHandle, NULL); 
    return 0; 
} 
+1

你可以發佈你的嘗試嗎?這可能會說明你在說什麼:) – qdii

+0

如果你陳述你正在使用的平臺,它可能也會有所幫助。 –

+4

你真的*應該爲此使用Boost.Thread或標準線程庫。如果你不這樣做,你最終會得到一個不太理想的解決方案,否則你將不得不重新實現這些庫已經具備的功能。 – Mankarse

回答

12

你可以通過一個靜態成員函數的並行線程,和對象作爲參數的一個實例。成語如下:

class Parallel 
{ 
private: 
    pthread_t thread; 

    static void * staticEntryPoint(void * c); 
    void entryPoint(); 

public: 
    void start(); 
}; 

void Parallel::start() 
{ 
    pthread_create(&thread, NULL, Parallel::staticEntryPoint, this); 
} 

void * Parallel::staticEntryPoint(void * c) 
{ 
    ((Parallel *) c)->entryPoint(); 
    return NULL; 
} 

void Parallel::entryPoint() 
{ 
    // thread body 
} 

這是一個pthread示例。你可以很容易地適應它使用std :: thread。

+0

恩......爲什麼staticEntryPoint調用另一個函數內的線程體?爲什麼不在staticEntryPoint裏面做呢? – user1701840

+1

@ user1701840:線程主體*可以放在'staticEntryPoint'中,但由於它是一個靜態函數,它可能不太方便(因爲成員訪問必須以'c->'爲前綴)。 – Mankarse

+0

恩,讓我試試。謝謝! – user1701840

7
#include <thread> 
#include <string> 
#include <iostream> 

class Class 
{ 
public: 
    Class(const std::string& s) : m_data(s) { } 
    ~Class() { m_thread.join(); } 
    void runThread() { m_thread = std::thread(&Class::print, this); } 

private: 
    std::string m_data; 
    std::thread m_thread; 
    void print() const { std::cout << m_data << '\n'; } 
}; 

int main() 
{ 
    Class c("Hello, world!"); 
    c.runThread(); 
} 
+0

快速提問:爲什麼我需要將'this'傳遞給線程構造函數? – Mushy

+0

因爲'Class :: print'是一個非靜態成員函數,所以它必須在一個對象上運行。如果你不告訴它,新線程應該如何知道哪個對象要調用它? –

+0

感謝您對上述解釋。我被'std :: thread'構造函數搞糊塗了,它似乎需要'rvalues',這裏'm_thread = std :: thread(&Class :: print,this);''''''''''''''''lvalue'參考被傳入。你請爲我澄清這一點?如果您願意,我會提出一個問題讓您回答; – Mushy

相關問題