//TODO
#include <iostream>
#include <thread>
std::thread::id main_thread_id = std::this_thread::get_id();
void hello()
{
std::cout << "Hello Concurrent World\n";
if (main_thread_id == std::this_thread::get_id())
std::cout << "This is the main thread.\n";
else
std::cout << "This is not the main thread.\n";
}
void pause_thread(int n) {
std::this_thread::sleep_for(std::chrono::seconds(n));
std::cout << "pause of " << n << " seconds ended\n";
}
int main() {
std::thread t(hello);
std::cout << t.hardware_concurrency() << std::endl;//可以并发执行多少个(不准确)
std::cout << "native_handle " << t.native_handle() << std::endl;//可以并发执行多少个(不准确)
t.join();
std::thread a(hello);
a.detach();
std::thread threads[5]; // 默认构造线程
std::cout << "Spawning 5 threads...\n";
for (int i = 0; i < 5; ++i)
threads[i] = std::thread(pause_thread, i + 1); // move-assign threads
std::cout << "Done spawning threads. Now waiting for them to join:\n";
for (auto &thread : threads)
thread.join();
std::cout << "All threads joined!\n";
}
上述代码:是std::thread的使用,结果编译报错信息如下:
问题分析:查看错误提示,发现thread不是命名空间std的一个成员,那么我们知道thread很明显是std的成员,那么久只有一种可能:即没有引入相关的头文件,但是检查发现,头文件也有。又知道std::thread为c++11新特性,就有可能是编译器不支持c++11。因此,尝试解决。
解决步骤(三步):
1、打开Project -> Properties -> C/C++ General -> Path and Symbols -> Tab [Symbols]
. 添加 symbol : __cplusplus 并设定它的值为:201103L(两个下划线)
2、project右键-> c/c++ build ->Settings -> GCC C++ Compiler -> Miscellaneous -> Other flags后面加上 -std=c++11
3、Window-> Preference -> Build -> Settings ->Discovery -> CDT GCC Built-in Compiler Settings MinGW(shared) ->(command to get compiler specs) ${COMMAND} -E -P -v -dD "${INPUTS}" -std=c++11
哈哈,完美解决编译问题,但是当我点击运行时,又爆了错误,怎么肥事?
经过长时间的摸索,总有找到原因了,需要指定thread
因为程序在运行时,还需要链接库,因此解决方案:
在上面第二步的后面继续添加 project右键-> c/c++ build ->Settings -> GCC C++ Compiler -> Miscellaneous -> Other flags后面加上 -std=c++11 -pthread
注意 别忘了在链接库中同样也要添加-pthread,所以还要执行下面一步:
bug解决