[英]Implementation of Threads in c++
我試圖在 c++ 中使用線程維護兩個函數(Visual Studio 支持#include 庫),當我運行沒有參數的函數時,它運行良好,但有參數時它會彈出錯誤。 代碼是:
void fun(char a[])
{}
int main()
{
char arr[4];
thread t1(fun);
//(Error 1 error C2198: 'void (__cdecl *)(int [])' : too few arguments for call)
thread t2(fun(arr));
//Error 1 error C2664: std::thread::thread(std::thread &&) throw()' :
//cannot convert parameter 1 from'void' to 'std::thread &&'
//Second Error is 2 IntelliSense: no instance of constructor
// "std::thread::thread" matches the argument list argument types are: (void
return 0;
}
幫我處理這個。
這是std::thread
構造函數的簽名(實際上是模板函數):
template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );
這意味着您必須提供一個Callable
(即您可以在其上使用()
任何內容)。 fun
是可以調用的,因為它是一個函數。 但是,表達式fun(arr)
並非如此,因為它表示應用於參數的函數,該函數產生類型為void
( fun
的返回類型)。 而且,在不調用您的函數的表達式thread(fun)
。 它被傳遞到新創建的線程, 然后執行。 如果表達式thread(fun(arr))
是有效的,則表達式fun(arr)
將在創建新線程之前求值,並且該線程將僅獲取fun(arr)
的結果,而不是函數本身。
但是C ++標准庫讓您滿意。 前面提到的構造函數有一個名為args
的參數包(即參數的可變長度列表),可讓您為線程函數提供參數。 因此,您應該使用:
thread t2(fun, arr);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.