2017-02-14 80 views
-1

我知道這個問題出現類似已經回答的,但自從給他們回答不工作對我來說,我不認爲這個問題是其中的一個dublicate調用帶參數不可能

螺紋功能

我很清楚,我該如何調用C++函數作爲一個具有一個或多個參數的線程已被多次回答 - 無論是在這裏還是在各種教程中 - 並且在任何情況下答案都是簡單的這是做它的方式:

(示例直接從this question

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

using namespace std; 

// The function we want to execute on the new thread. 
void task1(string msg) 
{ 
    cout << "task1 says: " << msg; 
} 

int main() 
{ 
    // Constructs the new thread and runs it. Does not block execution. 
    thread t1(task1, "Hello"); 

    // Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution. 
    t1.join(); 
} 

但是我已經嘗試copypasting這兩個代碼和更多(或多或少相同)如何做到這一點的例子,但是,每次我編譯(通過這樣的例子g++ test.cpp -o test.app(必須添加.app我在Mac上(請注意,這種編譯方式實際上對我很有用,而且錯誤不是我不知道如何編譯C++程序)))這樣的程序我得到這個錯誤消息:

test.cpp:16:12: error: no matching constructor for initialization of 'std::__1::thread' 
    thread t1(task1, "Hello"); 
     ^~~~~~~~~~~~~~~ 
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/thread:389:9: note: candidate constructor template not viable: requires single argument '__f', but 
     2 arguments were provided 
thread::thread(_Fp __f) 
     ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/thread:297:5: note: candidate constructor not viable: requires 1 argument, but 2 were provided 
    thread(const thread&); 
    ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/thread:304:5: note: candidate constructor not viable: requires 0 arguments, but 2 were provided 
    thread() _NOEXCEPT : __t_(0) {} 

我的問題就是爲此,我在做什麼錯相比,所有誰possitively可以使線程功能與參數的人,因爲我還沒有發現人experiancing類似的問題問任何問題,我不認爲對這個問題的很多下如何調用帶參數的

螺紋功能據我所知的副本,使用線程沒有按」 t需要任何特定的編譯器標誌,因爲我完全可以使用沒有參數的線程函數運行程序,所以不能聲稱我的計算機或編譯器完全可以使用線程。

+0

如果你做'g ++ --version'它報告什麼?你有沒有完全支持C++ 11(添加'std:thread'的標準)的Clang的非常舊的版本(在macOS'gcc'和'g ++'通常是Clang編譯器的別名)? –

+0

更改線程處理程序採取'char const *' –

+3

添加編譯器開關-std = C++ 11。 –

回答

1

根據gcc版本,您應該添加編譯器開關-std = C++ 11或-std = C++ 0x。

1

我能夠用C++ 14編譯它here

,並得到輸出如下。

task1 says: Hello 

編譯使用-std=c++11標誌或以上。