'C++ in vscode: error: no matching constructor for initialization of 'std::thread'

I just started to use vscode and I did a tutorial about multithreading in c++. The code below is just the same as the tutorial and I'm sure the code works in visual studio 2017.

#include <iostream>
#include <thread>
#include <string>
#include <mutex>
#include <fstream>
using namespace std;
std::mutex mu;
class LogFile{
    std::mutex mu;
    ofstream f;
    public:
        LogFile(){
            f.open("log.txt");
        }
        void p(string msg, int i){
            std::lock_guard<mutex> locker(mu);
            f << msg << i << endl;
        }
};

void function_1(LogFile& log){
    for(int i=0;i>-100;i--)
        log.p("from t1: ", i);
}
int main(){
    LogFile log;
    std::thread t1(function_1, std::ref(log));
    for (int i=0;i<100;i++)
        log.p("from main: ", i);
    t1.join();
    return 0;
}

the error is:

test.cpp:27:17: error: no matching constructor for initialization of 'std::thread'
    std::thread t1(function_1, std::ref(log));
                ^  ~~~~~~~~~~~~~~~~~~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/thread:408: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/include/c++/v1/thread:289: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/include/c++/v1/thread:296:5: note: candidate constructor not viable: requires 0 arguments, but 2 were provided
    thread() _NOEXCEPT : __t_(_LIBCPP_NULL_THREAD) {}
    ^
1 error generated.

Someone help me! Thanks!

c++


Solution 1:[1]

Your code is correct, so this seems to be an issue with xcode.

  • Are you using the latest version of XCode?
  • Did you set the standard version to C++11? (commandline opnion: -std=c++11)
  • Is XCode using an up-to-date version of the C++ Standard Library?

Solution 2:[2]

I compiled with -std=c++11 flag on Mac and the problem was solved.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alecto Irene Perez
Solution 2 Benjamin Ronneling