-2

I am learning to use threading so I am trying to run code utilizing the thread class so that I can run functions concurrently. However, trying to compile it in the terminals terminal, it says that thread and its object t1 is not declared.

 threading.cpp:16:5: error: 'thread' was not declared in this scope
     thread t1(task1, "Hello");
     ^~~~~~
 threading.cpp:21:5: error: 't1' was not declared in this scope
     t1.join();

I thought g++ doesn't support it but I also include in its argument to support c++11

  g++ -std=c++11 threading.cpp

Any idea what I should I do about this error?

(OS: windows, gcc version 6.3.0)

Code is provided below(an example from a website):

#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");

    // Do other things...

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

1 Answers1

0

Any idea what I should I do about this error?

Your code compiles and runs fine with a recent version of GCC (coliru.com). And the same is true for older versions (e.g. GCC 6) and with -std=c++11. Your problem must be elsewhere:

  • Perhaps you're using an extremely old compiler?
  • Perhaps your C++ standard library headers are not installed?
  • Perhaps your C++ standard library headers are located someplace unexpected? That could happen if you're using a custom-installed version of the compiler or standard library.
einpoklum
  • 118,144
  • 57
  • 340
  • 684