如何使用#include <thread>编译代码

q09*_*987 7 c++ multithreading

我正在尝试编译一些使用线程的C++代码:

#include <iostream>
#include <thread>
void hello()
{
    std::cout<<"Hello Concurrent World\n";
}

int _main(int argc, _TCHAR* argv[])
{
    std::thread t(hello);
    t.join();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译时出错:

c:\temp\app1\app1\app1.cpp(6): fatal error C1083: Cannot open 
include file: 'thread': No such file or directory


~/Documents/C++ $ g++ -o thread1 thread1.cpp -D_REENTRANT -lpthread
In file included from /usr/include/c++/4.5/thread:35:0,
                 from thread1.cpp:2:
/usr/include/c++/4.5/bits/c++0x_warning.h:31:2: error: #error This file 
requires compiler and library support for the upcoming ISO C++ standard, 
C++0x. This support is currently experimental, and must be enabled with 
the -std=c++0x or -std=gnu++0x compiler options.
Run Code Online (Sandbox Code Playgroud)

我该如何解决这些错误?

Mat*_*lia 9

<thread>和标准线程支持是一项新功能(在C++ 11标准中定义).对于g ++,您必须启用它添加-std=c++0x到命令行,如错误消息中所述.

此外,您使用的是非标准(Microsoft特定)main,使用"classic" main和normal char:

// thread1.cpp
#include <iostream>
#include <thread>

void hello()
{
    std::cout<<"Hello Concurrent World\n";
}

int main(int argc, char * argv[])
{
    std::thread t(hello);
    t.join();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

请注意,并非所有C++ 11功能都可在当前编译器中使用; 就g ++而言,您可以在此处找到其实现的状态.