2

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!

fuyao
  • 33
  • 1
  • 3
  • pretty sure Jorge's C++11 answer is right, here's a duplicate question: https://stackoverflow.com/questions/27606782/cant-pass-parameters-to-stdthread – kmdreko Mar 27 '19 at 04:26
  • @kmdreko yes you are pretty right, sorry I didn't find this question before. Thanks! – fuyao Mar 27 '19 at 05:07

3 Answers3

4

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?
Alecto Irene Perez
  • 10,321
  • 23
  • 46
1

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

1

According to Introductory Videos for C++ of VS Code, the default configuration on the tasks.json on Mac doesn't specify C++ Version, and - dependent on you'r macOs version, consider specifying libc as well (When to specify libstdc).

The Documentation says you should add in tasks.json under args

"-std=c++17",

"-stdlib=libc++",
joepol
  • 744
  • 6
  • 22