[英]How to use std::thread?
當我像這樣使用std::thread
:
func()
{
std::thread(std::bind(&foo, this));
}
線程對象在堆棧中分配,並在func()
返回時銷毀。 所以我嘗試像這樣使用它:
func()
{
std::thread* threadPtr = new std::thread(std::bind(&foo, this));
}
我應該在哪里delete threadPtr
? 以及如何創建最初被掛起的線程?
如果希望線程獨立運行,則需要在對象上使用detach()
方法。 否則,如果在線程仍在運行時銷毀了對象,則thread
析構函數將終止您的程序。
線程在創建后即開始運行。 您不能在掛起狀態下創建線程對象。 您可以存儲用於創建線程的參數,而不是實際創建線程(可能使用例如std::function
),或者使其在互斥量或條件變量上阻塞,直到准備好讓其運行為止。
如何使用std :: thread?
這取決於您在線程中執行的操作,但是最有可能要使用join
。 也可以使用detach
但是必須注意確保它不使用任何在執行過程中可能被破壞的資源。
std :: thread(std :: bind(&foo,this));
這沒有任何意義。 您正在綁定(不必使用bind
) this
指針,但是&foo
不是指向成員函數的指針(看起來像&Foo::foo
)。 假設您打算使用指向成員函數的指針,那將意味着func
也是同一類的成員函數(即,由於它可以訪問this
指針),因此以下代碼為您提供了可以執行的示例。
#include <iostream>
#include <thread>
class Foo
{
public:
Foo() = default;
~Foo()
{
if (mThread.joinable())
{
mThread.join();
}
}
void foo()
{
std::cout << "Foo::foo\n";
}
void func()
{
if (mThread.joinable())
{
mThread.join();
}
// Creates the thread without using 'std::bind'
mThread = std::thread(&Foo::foo, this);
}
private:
std::thread mThread;
};
int main()
{
{
Foo f;
f.func();
f.func();
}
return 0;
}
Foo::foo
Foo::foo
我應該在哪里刪除threadPtr?
我不會動態分配線程,但是在上面的示例代碼中,您將在加入后將其刪除。
如何創建最初被掛起的線程?
C ++不直接支持此功能,但是您可以將平台特定的API與std::thread::native_handle
。 注意 ,如果您只想在一開始就阻塞一次,則可以使用同步原語來實現(例如,在運行實際線程之前在std::mutex
上阻塞)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.