Basic <thread> library functions not working!

The Codeler 40 Reputation points
2024-12-20T21:23:31.37+00:00

I was trying to create a code with threads, but it won't let me do that kind of thing.

The this_thread and thread global is non-accessible for creating new threads and ::sleep_for functions. I am pretty new to vs code so please help me. This is also not working in Code::Blocks which probably means it is my compiler. My complier is MinGW and I have the pthread extensions downloaded on it.

Here is the code that won't work on MinGW run applications, but will on online compilers such as online-cpp.com:

#include <iostream>
#include <chrono>
#include <thread>

using namespace std;

void wait(int seconds = 10) {
    this_thread::sleep_for(chrono::seconds(seconds));
}

int main() {
    cout << 6;
    thread branchoff(wait, 4);
	branchoff.join();
    auto x = 7;
    cout << x;
}

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,804 questions
0 comments No comments
{count} votes

Accepted answer
  1. Darran Rowe 1,236 Reputation points
    2024-12-20T22:51:16.3533333+00:00

    Since this is a Microsoft Visual C++ forums, there may not be the kind of expertise to give a full answer here.

    But please clarify what is meant by "not working" and "won't let me do that kind of thing".

    In Visual C++, the compiler needs to be set to C++20 mode, and this requires a command line option. This is the /std option.

    Looking at the GCC C++ Standards Support in GCC page, this states that -std=c++20 should be used to enable C++20 support, or -std=gnu++20 for C++20 with GNU extensions. Is one of these two options on the compiler command line?

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.