我對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;
}
你可以發佈你的嘗試嗎?這可能會說明你在說什麼:) – qdii
如果你陳述你正在使用的平臺,它可能也會有所幫助。 –
你真的*應該爲此使用Boost.Thread或標準線程庫。如果你不這樣做,你最終會得到一個不太理想的解決方案,否則你將不得不重新實現這些庫已經具備的功能。 – Mankarse